为多个元素添加事件侦听器并检测哪个元素触发了事件-jQuery

时间:2018-11-08 12:20:57

标签: javascript jquery event-listener

我在click中的多个元素上添加了jQuery事件监听器,效果很好:

$('#element1, #element2, #element3, #element4').on('click', function(){
  // do something with the clicked element
});

现在,我想找出正在单击的元素。我怎样才能做到这一点?非常感谢。

3 个答案:

答案 0 :(得分:2)

您可以按照

进行操作
$('#element1, #element2, #element3, #element4').on('click', function(){
       var ID = $(this).attr('id'); 
       alert('you clicked on #' +ID);
});

答案 1 :(得分:1)

您可以使用this或检查事件处理程序函数传递的 event target 属性:

使用this

$('#element1, #element2, #element3, #element4').on('click', function(event){
    console.log('The id of the clicked button is: ' +this.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="element1">Button1</button>
<button id="element2">Button2</button>
<button id="element3">Button3</button>
<button id="element4">Button4</button>

使用Event.target

$('#element1, #element2, #element3, #element4').on('click', function(event){
    console.log('The id of the clicked button is: ' +event.target.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="element1">Button1</button>
<button id="element2">Button2</button>
<button id="element3">Button3</button>
<button id="element4">Button4</button>

答案 2 :(得分:1)

您可以使用event.target

$('#element1, #element2, #element3, #element4').on('click', function(event){
    console.log(event.target)
});

阅读this以获得更多理解