Jquery get clicked element on delegated event
我见过类似的问题,但他们没有解决这个问题。我有一个看起来像这样的 html:
1 | <i class="fa fa-close"> |
所以,在委托事件触发后,我想获取
1 2 3 | $("#products").on("click",".delete_product", function(){ console.log($(this).hasClass(".delete_product")); } |
当然,控制台记录错误。如何获得点击的元素?
您需要使用事件的目标属性。这是代码,它将为您提供确切的 .delete_product.
1 2 3 4 5 | $("#products").on("click",".delete_product", function (ev) { var $t = $(ev.target); $t = $t.is('.delete_product') ? $t : $t.parents('.delete_product'); console.log($t.hasClass("delete_product")); }); |
试试这个:
1 2 3 4 5 6 7 8 9 | $(document).ready(function(){ $("#products").on("click",".delete_product", function(){ alert($(this).hasClass("delete_product")); }) }) |
最终代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <html> This is test <head> <style> </style> </head> <body> <i class="fa fa-close">Click Me! <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> $(document).ready(function(){ $("#products").on("click",".delete_product", function(){ alert($(this).hasClass("delete_product")); }) }) </body> </html> |
您不应该在
1 2 3 | $("#products").on("click",".delete_product", function(){ console.log($(this).hasClass('delete_product')); }); |
jQuery 确实提供了与选择器匹配的元素作为
When jQuery calls a handler, the
this keyword is a reference to the element where the event is being delivered; [...] for delegated events this is an element matchingselector .
仅供参考:当然还有另一种方法,您可以(并且应该)使用选择器(带点):
1 2 3 | $("#products").on("click",".delete_product", function(){ console.log($(this).is('.delete_product')); }); |