我的html是这样的:
<table class="ListCheck">
<tbody>
<tr>
<td>
<span class="listitem">
<input name="ctl00$MainContent$List$0" class="location" id="MainContent_List_0" type="checkbox">
<label for="MainContent_List_0">test</label></span>
</td>
<td>
<span class="listitem">
<input name="ctl00$MainContent$List$1" class="location" id="MainContent_List_1" type="checkbox">
<label for="MainContent_List_1">test</label></span>
</td>
<td>
<span class="listitem">
<input name="ctl00$MainContent$List$2" class="location" id="MainContent_List_2" type="checkbox">
<label for="MainContent_List_2">test</label></span>
</td>
</tr>
</tbody>
</table>
我正在尝试添加 javascript 以在标签上添加一个类,以便在选中复选框时应用一些 css
我的脚本是:
<script type='text/javascript'>
$('.listitem').each(function () {
$(this).children("input").addClass("location");
if ($(this).children("input").is(":checked"))
{
$(this).children('label').addClass("checked");
} else {
$(this).children('label').removeClass("checked");
}
});
</script>
但由于某种原因,它没有在运行时在标签上添加类。请查看我的代码并让我知道我缺少什么。 TIA。
最佳答案
您可以使用 next()
访问相应<label>
的方法如下:
$('input[type="checkbox"]').click(function () {
$(this).next().toggleClass("checked");
});
关于Javascript 在标签上添加 css 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22489545/