如何将函数附加到带有参数的事件处理程序
How do I attach a function to an event handler with parameters
我正在用jQuery编写,并希望在单击元素时发生一些事情。我想要调用的函数需要参数,并且必须始终监视事件,因此处理程序在$(document).ready()中。我的意思是:
"use strict"
$(document).ready(function(){
$("<button>").each(
$(this).click(doSomething)
);
});
function doSomething(message){
alert(message);
}
问题是doSomething需要一个它可以提醒的消息。但是,如果我将代码更改为:
$(document).ready(function(){
$("<button>").each(
$(this).click(doSomething("Hello world"))
);
});
function doSomething(message){
alert(message);
}
当页面加载时,"Hello world"会被提醒,点击按钮什么都不会做。我如何保持第一种方式的行为,但传递一个参数的方法?
你需要传递一个匿名函数,然后用所需的参数调用你的函数:
$(document).ready(function(){
$("button").click(function() {
doSomething("Hello world!");
});
);
});
function doSomething(message){
alert(message);
}
请注意,我已经修改了选择器,使其选择现有的<button>
元素,而不是创建一个新的,并删除了不必要的.each()
,因为.click()
隐式迭代匹配的元素已经。
试试这个:
$("button").click(function(){
doSomething("Hello world");
});
function doSomething(message){
alert(message);
}
您需要bind-function。这是最近添加到ECMAScript的,如果它不可用,您需要提供它:
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
查看此页的参考:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
如果你包含了这段代码,你可以做以下的事情:
$(document).ready(function(){
$("button").click(doSomething.bind("Hello world"));
});
function doSomething(message){
alert(message);
}
你的代码中有很多错误,首先,$("<button>")
创建新的dom元素,而不是选择页面上现有的元素。关于这部分doSomething("Hello world")
-您立即评估代码,在Jquery点击引用中,您可以看到数据处理程序必须作为第一个参数。下面是正确的清单
$().ready(function(){
$("button").each(
$(this).click("Hello world",doSomething)
);
});
function doSomething(message){
alert(message);
}
相关文章:
- 检查事件处理程序参数
- 带有参数的Javascript事件处理程序
- 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件's”;这个“;上下文
- 将作用域绑定到事件处理程序,但保留原始参数
- 将参数传递给函数,同时保留事件处理程序
- 在动态创建的元素中包含参数的事件处理程序
- JS:删除带有接受参数的处理程序的事件侦听器
- 将参数传递给jQuery中的事件处理程序
- 如何将对象参数传递给事件处理程序
- 如何在事件处理程序中包含函数(及其参数),而不在页面加载时调用该函数
- 如何使用函数作为事件处理程序,以及如何使用参数直接调用函数
- 将其他参数传递给事件处理程序
- 在 .on('click') 事件处理程序中传递函数和函数参数
- 将参数从闭包传递给事件处理程序
- 当函数绑定在构造函数中时,如何在 ES6 React 中向事件处理程序添加参数
- 作用域和将参数传递给动态创建的事件处理程序时出现问题
- 在 HTML 中传递多个参数鼠标悬停事件处理程序
- 如何将参数传递到事件处理程序中以使其唯一
- 向事件处理程序函数添加参数
- "这个“;当我向事件处理程序函数添加参数时会发生更改