【发布时间】:2015-04-07 03:12:06
【问题描述】:
有没有办法使用 jquery 从<label> 元素中获取文本?因为我们可以使用 $(this).val(); 从中获取值,但无法对标签文本执行相同操作。
似乎我们应该能够在选择单选按钮时使用$(this) 查询<label> 文本,因为$(this) 在此期间知道它的值。
最初使用 case 语句并手动填写一些文本,但如果我们能够只插入标签文本,那么就不需要使用所有 case 语句了。
想法/建议?
html
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#accordion-second">What You Are Interested In Learning About</a>
</h4>
</div>
<div id="accordion-second" class="panel-collapse collapse">
<div class="panel-body">
<div class="radio">
<label><input type="radio" name="optradio2" value="2a">the Automotive Industry</label>
</div>
<div class="radio">
<label><input type="radio" name="optradio2" value="2b">the sports industry</label>
</div>
<div class="radio">
<label><input type="radio" name="optradio2" value="2c">the music industry</label>
</div>
</div>
</div>
</div>
jquery
<script>
$('[name="optradio2"]').on('change', function () {
$('#accordion-third').slideToggle();
$('#accordion-second').slideToggle();
//how do you get the label text
var labelText = $("label", this).text();
//current method but would prefer to just insert the label text
/*var value = $(this).val();
switch (value) {
case "2a":
$('#blank2', $('#myModal')).text('the automotive industry');
break;
case "2b":
$('#blank2', $('#myModal')).text('the sports industry');
break;
case "2c":
$('#blank2', $('#myModal')).text('the music industry');
break;
default:
alert("oops! something went wrong");
}*/
})
</script>
【问题讨论】:
-
$('input:radio[name=optradio2]:checked').closest('label').text(); -
这个解决方案也很有效。谢谢斯蒂芬!
标签: jquery html asp.net-mvc forms radio-button