jQuery 的 .click - 将参数传递给用户函数 [英] jQuery's .click - pass parameters to user function

查看:33
本文介绍了jQuery 的 .click - 将参数传递给用户函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 jQuery 的 .click 调用带参数的函数,但我无法让它工作.

I am trying to call a function with parameters using jQuery's .click, but I can't get it to work.

这就是我希望它的工作方式:

This is how I want it to work:

$('.leadtoscore').click(add_event('shot'));

哪个调用

function add_event(event) {
    blah blah blah }

如果我不使用参数,它会起作用,就像这样:

It works if I don't use parameters, like this:

$('.leadtoscore').click(add_event);
function add_event() {
    blah blah blah }

但我需要能够将参数传递给我的 add_event 函数.

But I need to be able to pass a parameter through to my add_event function.

我该如何做这件特定的事情?

How can I do this specific thing?

我知道我可以使用 .click(function() { blah },但我从多个地方调用了 add_event 函数并希望这样做.

I know I can use .click(function() { blah }, but I call the add_event function from multiple places and want to do it this way.

推荐答案

为了彻底,我遇到了另一个解决方案,它是 jQuery 单击事件处理程序.

For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.

它允许您将数据映射传递给事件对象,该对象自动通过 jQuery 作为第一个参数反馈给事件处理函数.数据映射将作为第一个参数传递给 .click() 函数,然后是事件处理函数.

It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click() function as the first parameter, followed by the event handler function.

这里有一些代码来说明我的意思:

Here's some code to illustrate what I mean:

// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);
}

我知道这个问题已经晚了,但之前的答案让我找到了这个解决方案,所以我希望它在某个时候对某人有所帮助!

I know it's late in the game for this question, but the previous answers led me to this solution, so I hope it helps someone sometime!

这篇关于jQuery 的 .click - 将参数传递给用户函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆