With jQuery code like:

$("#myid").click(myfunction);

function myfunction(arg1, arg2) {/* something */}

如何在使用jQuery时将参数传递给myfunction

推荐答案

The simplest way is to do it like so (assuming you don't want any of the event information passed to the function)...

$("#myid").click(function() {
    myfunction(arg1, arg2);
});

jsFiddle.

这将创建一个匿名函数,在触发click事件时调用该函数.这将依次调用myfunction()和您提供的参数.

If you want to keep the ThisBinding (the value of this when the function is invoked, set to the element which triggered the event), then call the function with call().

$("#myid").click(function() {
    myfunction.call(this, arg1, arg2);
});

jsFiddle.

您不能按照示例中的方式直接传递引用,否则它的单个参数将是jQuery event object.

If you do want to pass the reference, you must leverage jQuery's proxy() function (which is a cross browser wrapper for Function.prototype.bind()). This lets you pass arguments, which are bound before the event argument.

$("#myid").click($.proxy(myfunction, null, arg1, arg2));   

jsFiddle美元.

在本例中,myfunction()ThisBinding完好无损地执行(null不是对象,因此使用触发事件的元素的正常this值),以及参数(按顺序)arg1arg2,最后是jQuery event对象,如果不需要它,您可以忽略它(甚至不要在函数的参数中命名它).

You could also use use the jQuery event object's data to pass data, but this would require modifying myfunction() to access it via event.data.arg1 (which aren't function arguments like your question mentions), or at least introducing a manual proxy function like the former example or a generated one using the latter example.

Jquery相关问答推荐

为什么如果使用转换规模,juserui可拖动遏制不起作用

使用 Ajax 列出数据(仅显示最后的数据)

子 li 元素的点击事件

从文本区域获取值

如何确定 jQuery 中匹配元素的元素类型?

在 jQuery 事件中控制this的值

如何在 jQuery 中获取浏览器滚动位置?

jquery清除输入默认值

使用 jQuery DataTables 时禁用最后一列的排序

jQuery DataTables:延迟搜索直到输入 3 个字符或单击按钮

如何检测是否安装了 Flash,如果没有,显示一个隐藏的 div 通知用户?

$(document).on("click"... 不工作?

判断 JS 对象中是否存在键

在 bootstrap 弹出窗口中包含表单?

如何在按键事件后获取 jQuery .val()?

Uncaught TypeError: undefined is not a function on loading jquery-min.js

jQuery 发送字符串作为 POST 参数

使用 jquery 禁用文本框?

Ajax 处理中的无效 JSON 原语

使用 JQuery 判断组中是否没有选中单选按钮