我只想将事件绑定(bind)到 jQuery 中的“页面”。
问题是,当使用 addClass
时,代码不仅针对“页面”执行,而且针对所有后代执行。我想仅当 addClass
用于“pages”div 时触发该事件。我怎样才能做到这一点?
//https://stackoverflow.com/a/31859060/2947462
(function( func ) {
$.fn.addClass = function() { // replace the existing function on $.fn
func.apply( this, arguments ); // invoke the original function
this.trigger('eventAddClass'); // trigger the custom event
return this; // retain jQuery chainability
}
})($.fn.addClass); // pass the original function as an argument
$(document).on( "eventAddClass", 'div[data-role="page"]', function(event) {
//code - do some stuff
});
最佳答案
你可以这样做。
这就是事件冒泡。读这个~https://www.sitepoint.com/event-bubbling-javascript/
$(document).on( "eventAddClass", 'div[data-role="page"]', function(event) {
if(event.target !== event.currentTarget) return;
// your custom code
});
关于jQuery 选择器(仅选择目标,不选择后代),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52221055/