Javascript 将参数传递给 jquery 中的 click() 和 bind() 事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3994527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:03:52  来源:igfitidea点击:

Passing parameters to click() & bind() event in jquery?

javascriptjqueryevents

提问by Prashant

I want to pass few parameters to Click() event in jquery, I tried following but its not working,

我想在 jquery 中将几个参数传递给 Click() 事件,我尝试了以下但它不起作用,

commentbtn.click(function(id, name){
    alert(id);
});

And also if we use bind then how we'll do that

而且如果我们使用 bind 那么我们将如何做到这一点

commentbtn.bind('click', function(id, name){
    alert(id);
});

Please help!

请帮忙!

回答by Anurag

see event.data

看到event.data

commentbtn.bind('click', { id: '12', name: 'Chuck Norris' }, function(event) {
    var data = event.data;
    alert(data.id);
    alert(data.name);
});

If your data is initialized before binding the event, then simply capture those variables in a closure.

如果您的数据在绑定事件之前已初始化,那么只需在闭包中捕获这些变量即可。

// assuming id and name are defined in this scope
commentBtn.click(function() {
    alert(id), alert(name);
});

回答by dxh

From where would you get these values? If they're from the button itself, you could just do

你从哪里得到这些值?如果它们来自按钮本身,你可以这样做

commentbtn.click(function() {
   alert(this.id);
});

If they're a variable in the binding scope, you can access them from without

如果它们是绑定范围内的变量,则可以从不访问它们

var id = 1;
commentbtn.click(function() {
   alert(id);
});

If they're a variable in the binding scope, that might changebefore the click is called, you'll need to create a new closure

如果它们是绑定范围中的变量,则在调用单击之前可能会发生变化,您需要创建一个新的闭包

for(var i = 0; i < 5; i++) {
   $('#button'+i).click((function(id) {
      return function() {
         alert(id);
      };
   }(i)));
}

回答by Jakub Konecki

var someParam = xxxxxxx;

commentbtn.click(function(){

    alert(someParam );
});

回答by Haroldo Macedo

An alternative for the bind() method.

bind() 方法的替代方法。

Use the click() method, do something like this:

使用 click() 方法,执行如下操作:

commentbtn.click({id: 10, name: "Jo?o"}, onClickCommentBtn);

function onClickCommentBtn(event)
{
  alert("Id=" + event.data.id + ", Name = " + event.data.name);
}

Or, if you prefer:

或者,如果您更喜欢:

commentbtn.click({id: 10, name: "Jo?o"},  function (event) {
  alert("Id=" + event.data.id + ", Nome = " + event.data.name);
});

It will show an alert box with the following infos:

它将显示一个警告框,其中包含以下信息:

Id = 10, Name = Jo?o