我有以下代码:
<div class="top">
<label id="_first"><input type="checkbox" class="AA" id="first">FIRST</label>
<label id="_second"><input type="checkbox" class="BB" id="second">SECOND</label>
<label id="_first"><input type="checkbox" class="AA" id="third">THIRD</label>
</div>
如何在单击标签时监听 mousedown
事件,然后获取该输入的 ID?
例如,如果我将指针单击到“THIRD”一词上,我想将一个变量设置为输入 id = third
。我只想在存在某个类(即 .BB
)的输入时查找 ID。
我尝试过这样的事情:
$('label .BB').on('mousedown', function(){
var sel = $(this).attr('id'); // doesn't grab id of the adjacent input
});
最佳答案
替代for
属性设置为 id
child 的input
id
的元素在<label>
元素。获取.htmlFor
的label
元素位于 mousedown
事件。
$("label").on("mousedown", function(e) {
console.log(this.htmlFor)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top">
<label for="first"><input type="checkbox" class="AA" id="first">FIRST</label>
<label for="second"><input type="checkbox" class="BB" id="second">SECOND</label>
<label for="third"><input type="checkbox" class="AA" id="third">THIRD</label>
</div>
关于javascript - 如何在 mousedown 事件后找到标签旁边的输入的 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42217767/