$(document).ready(function(){
$('html').addClass('js');
var contactForm = {
init: function(){
$('<button></button>',{
text: 'contact me'
}).appendTo('article')
**.on('click', this.show);**
},
show: function(){
console.log('show is clicked');
}
}
contactForm.init();
});在onClick调用中,为什么.on('click', this.show());会在.on('click', this.show());加载时立即执行,而稍后的get只在单击按钮时执行。
发布于 2013-08-18 13:31:08
末尾的括号意味着应该立即调用前面的函数。如果没有括号,它将成为对函数的引用。
因此,on('click', this.show());将意味着在设置click处理程序时在加载时调用show函数,并将其返回值设置为事件处理程序。
其中,on('click', this.show);为单击处理程序提供了对show函数的引用,当click事件发生时将调用该函数。
最佳实践是只将函数的引用传递给事件处理程序--即。后一个例子。
发布于 2013-08-18 13:32:52
‘'on()’是一个函数(在本例中)有两个参数。
this.show向名为show的函数传递一个引用。
this.show()调用函数并传递返回值。
https://stackoverflow.com/questions/18299604
复制相似问题