[英]adding event listener for multiple elements and detecting which element is triggering the event - jQuery
我在jQuery
中的多个元素上添加了click
事件监听器,效果很好:
$('#element1, #element2, #element3, #element4').on('click', function(){
// do something with the clicked element
});
现在,我想找出正在单击的元素。 我怎样才能做到这一点? 非常感谢你。
您可以通过以下方式获得它
$('#element1, #element2, #element3, #element4').on('click', function(){
var ID = $(this).attr('id');
alert('you clicked on #' +ID);
});
您可以使用this
或检查事件处理程序函数的传递事件的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>
您可以使用event.target
$('#element1, #element2, #element3, #element4').on('click', function(event){
console.log(event.target)
});
阅读这对于更多的理解
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.