几周前,我痛苦地能够将按钮动态添加到具有自己的 .on('click'.. 处理程序的 HTML DOM 对象,并使用 e.stopPropgation 来阻止这些新的子元素触发事件。
我做的奇怪的事情是调用一个没有任何括号的函数。我不知道为什么我这样做或为什么它有效,或者为什么当我附加括号时它不起作用。我想知道我做的事情是否是出于侥幸而不是设计(现在我将为其添加评论)。
事情是这样的:
//Container is the parent element
// var buttons stores the buttons with class 'buttons'
$('.container').on('click', function(){
$(buttons).appendTo($(this)).fadeIn(500).find('.buttons').click(tableButton);
});
function tableButton(e){
e.stopPropagation();
//do stuff
}
我不明白为什么我毫无争议地编写了对 tableButton 的调用,也不明白为什么它工作得很好。我尝试将语法更改为
.find('.buttons').on('click', function(e){
tableButton(e);
});
但之后它就不再起作用了。
感谢任何帮助!
最佳答案
它之所以有效,是因为您将一个函数传递给点击处理程序,而不是自己调用该函数(())示例:
var testFunction = function(msg) {
alert(msg);
}
var functionCaller = function(functionToCall) {
functionToCall('hello!');
}
functionCaller(testFunction);
functionCaller 将消息参数传递给 testFunction(),但我们只将 testFunction 传递给 functionCaller(不带参数)
对于不起作用的部分,函数名称不是tableButton()而不是tableButtons()吗?
关于JavaScript 调用不带括号的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24976856/