用于复选框标签的Jquery选择器

Jquery selector for the label of a checked checkbox

本文关键字:Jquery 选择器 标签 复选框 用于      更新时间:2023-09-26

我们可以选择复选框(在jQuery中)如下:

jQuery(:checked)

但是如何在jQuery中选择选中的复选框的标签呢?

复选框自带文本(在asp.net中它DOES)

jQuery(":checked").next('span').html() //next or prev ( depends n direction)

复选框文本为label元素。只需搜索for属性的数学表达式:

在html中看起来像:

<input type="checkbox" name="chk" />
<label for="chk">Checkbox 1</label>

你可以这样找到:

jQuery('input[type=checkbox]:checked').map(function() {
    return $('label[for=' + $(this).attr('name') + ']');
});

这将返回所有复选框标签。标签不需要是复选框附近的下一个或上一个元素。

假设你有这个html

<label>Label</label>
<input type="checkbox" checked="checked"> test </input>
<label>Label 2</label>
<input type="checkbox" > test 2 </input>
<label>Label 3</label>
<input type="checkbox" > test 3</input>

可以使用

找到标签
$("input:checked").prev('label');

*使用.next如果你有标签后的复选框在你的html

*使用.parent如果你把复选框包装在标签元素