Javascript 如何在mousedown事件后找到标签旁边的输入id?
我有以下代码:Javascript 如何在mousedown事件后找到标签旁边的输入id?,javascript,jquery,label,mousedown,Javascript,Jquery,Label,Mousedown,我有以下代码: <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"&g
<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>
$('label input.BB')。单击(函数(e){
//如果(e.target.type!='checkbox'){//检查复选框是否不激发,请单击
警报($(this.attr('id'))//将此上下文用于查找
//}
})
第一
第二
第三
将替换为
元素处id
的子输入元素的属性设置为id
。在mousedown
事件中获取label
元素的.htmlf
$(“标签”)。在(“鼠标向下”,函数(e)上{
console.log(this.htmlFor)
})
第一
第二
第三
您可以使用标签的属性,该属性将与复选框的id
属性匹配
HTML
使用本机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;
}
你的输入是什么?嗯,这似乎有效,但如何防止它触发两次?你能用mousedown
选择器来选择它吗?酷!如果我只想在标签上运行,然后在class=BB
的输入上运行该怎么办?您是否可以修改jquery选择器,使其仅包含使用label>input.BB的单击?或者类似的事情?你可以做一些像添加条件的更新。您想只显示带有类BB的输入吗?是的,我只想听一下带有类BB的输入的标签上的点击,忽略没有这个类的标签点击。
<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>
$('label').on('click', function() {
var getId = $(this).attr('for');
console.log(getId)
})
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;
}