我click
在多个元素上添加了事件侦听器,jQuery
其中工作正常:
$('#element1, #element2, #element3, #element4').on('click', function(){
// do something with the clicked element
});
现在我想找出正在单击的元素。我怎样才能做到这一点?非常感谢你。
您可以使用this
或检查事件处理函数的传递事件的目标属性:
使用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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句