如何在jQuery中将参数传递给事件处理程序?

编程入门 行业动态 更新时间:2024-10-23 19:30:39
本文介绍了如何在jQuery中将参数传递给事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用jQuery代码:

With jQuery code like:

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

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

How do I pass arguments to myfunction while using jQuery?

推荐答案

最简单的方法是这样做(假设您不希望任何事件信息传递给函数)...

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 。

这会创建一个匿名函数,在点击事件被触发时调用。这将依次使用您提供的参数调用 myfunction()。

This create an anonymous function, which is called when the click event is triggered. This will in turn call myfunction() with the arguments you provide.

如果您想保留 ThisBinding (这个当调用函数时,设置为触发事件的元素),然后用 call() 。

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 。

You can't pass the reference directly in the way your example states, or its single argument will be the jQuery event object.

如果你做想传递引用,你必须利用jQuery的 proxy() function(这是 Function.prototype.bind() )。这允许您传递参数,这些参数在 事件参数之前绑定。

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 不是对象,所以正常此值触发事件的元素的使用),以及参数(按顺序) arg1 , arg2 最后jQuery 事件对象,如果不需要,可以忽略它(甚至不要在函数的参数中命名)。

In this example, myfunction() would be executed with its ThisBinding intact (null is not an object, so the normal this value of the element which triggered the event is used), along with the arguments (in order) arg1, arg2 and finally the jQuery event object, which you can ignore if it's not required (don't even name it in the function's arguments).

您还可以使用jQuery 事件对象的 数据 传递数据,但这需要修改 myfunction()才能通过 event.data.arg1 (这不是函数参数,就像你的问题提到的那样),或者至少引入了像前一个例子那样的手动代理函数o使用后一个例子生成一个。

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中将参数传递给事件处理程序?

本文发布于:2023-11-23 19:44:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622658.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   参数   事件   程序   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!