我有以下代码:
<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
});
答案 0 :(得分:1)
将for
元素设置为id
元素的input
元素的id
替换<label>
元素。在.htmlFor
活动中获取label
个mousedown
元素。
$("label").on("mousedown", function(e) {
console.log(this.htmlFor)
})
&#13;
<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>
&#13;
答案 1 :(得分:0)
$('label input.BB').click(function(e) {
//if(e.target.type != 'checkbox' ){//check for checkbox dont fire click
alert($(this).attr('id'))//use this context with find
//}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
将此上下文与find
一起使用答案 2 :(得分:0)
您可以使用标签的for
属性,该属性与复选框的id
属性相匹配
HTML
<div class="top">
<input type="checkbox" class="AA" id="first">
<label for="first">First</label>
<input type="checkbox" class="BB" id="second">
<label for="second">Second</label>
<input type="checkbox" class="AA" id="third">
<label for="third">Third</label>
</div>
JS
$('label').on('click', function() {
var getId = $(this).attr('for');
console.log(getId)
})
答案 3 :(得分:0)
使用原生javascript方法
var first = document.getElementById('_first');
first.setAttribute('onclick','myFunction()');
function myFunction(){
var first = document.getElementById('_first');
var firstID = first.getAttribute('id');
//or
//var firstID = first.id;
}