当我点击按钮时,它会显示 Bruce Wayne is Batman
。在最后一个 jQuery 行中,对于“click”函数,如果我传递参数“guy”,jQuery 将不会运行,但如果我不传递参数,我会得到 undefined
。我究竟做错了什么?提前致谢。
$("div").on('click', 'button', click(guy));
jsFiddle 链接、HTML 和 JS 如下。
https://jsfiddle.net/wrj5w1Lk/
<div>
<button>
Click Me! Click Me!
</button>
<p>Hello</p>
</div>
$(document).ready(function() {
var Person = function(first, last, secret) {
this.first = first;
this.last = last;
this.secret = secret;
}
var guy = new Person("Bruce", "Wayne", "Batman");
var click = function(person) {
$(this).closest('div').find('p').text(person.first + " " + person.last + " is " + person.secret);
};
$("div").on('click', 'button', click(guy));
});
最佳答案
您有两个问题,首先您需要将对 click()
的调用包装在匿名函数中。其次,您需要将当前 button
元素的引用传递给 click()
函数。试试这个:
var click = function($element, person) {
$element.closest('div').find('p').text(person.first + " " + person.last + " is " + person.secret);
};
$("div").on('click', 'button', function() {
click($(this), guy);
});
关于javascript - 在 .on ('click' ) 事件处理程序中传递函数和函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35992066/