我在click
中的多个元素上添加了jQuery
事件监听器,效果很好:
$('#element1, #element2, #element3, #element4').on('click', function(){
// do something with the clicked element
});
现在,我想找出正在单击的元素。我怎样才能做到这一点?非常感谢你。
最佳答案
您可以使用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>