如何在mousedown事件后找到标签旁边输入的id?

时间:2017-02-14 04:16:02

标签: 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"><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
});

4 个答案:

答案 0 :(得分:1)

for元素设置为id元素的input元素的id替换<label>元素。在.htmlFor活动中获取labelmousedown元素。

&#13;
&#13;
$("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;
&#13;
&#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)
})

DEMO

答案 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;
}