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

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

问题描述

我尝试使用jQuery的.click参数调用一个函数,但是我无法实现它。



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



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



调用

 函数add_event(event){
blah blah blah}

它可以工作,如果我不使用参数,像这样:

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

但是我需要能够通过一个参数传递给我的 add_event 函数。



我该怎么做这个特定的事情?



我知道我可以使用 .click(function(){blah} ,但我把 add_event 函数来自多个位置,并希望这样做。

解决方案

遇到了另一个解决方案,它是jQuery 单击事件处理程序版本1.4.3中引入的功能的一部分。

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

以下是一些代码给我说明我的意思:

  //说你的选择器和单击处理程序看起来像这样... 
$( some selector)。click({param1:Hello,param2:World},cool_function);

//在你的函数中,只需抓住事件对象并发疯......
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
}

我知道这个问题在游戏中已经晚了,我到这个解决方案,所以我希望它可以帮助别人!


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'));

which calls

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 }

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

How can I do this specific thing?

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.

解决方案

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.

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天全站免登陆