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

Pra*_*ant 55 javascript jquery events

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

commentbtn.click(function(id, name){
    alert(id);
});
Run Code Online (Sandbox Code Playgroud)

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

commentbtn.bind('click', function(id, name){
    alert(id);
});
Run Code Online (Sandbox Code Playgroud)

请帮忙!

Anu*_*rag 124

see event.data

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

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);
});
Run Code Online (Sandbox Code Playgroud)

  • +1用于回答应该问的问题. (13认同)
  • hahhha,"查克诺里斯"让我的一天,哈哈+1 :) (5认同)

Dav*_*und 20

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

commentbtn.click(function() {
   alert(this.id);
});
Run Code Online (Sandbox Code Playgroud)

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

var id = 1;
commentbtn.click(function() {
   alert(id);
});
Run Code Online (Sandbox Code Playgroud)

If they're a variable in the binding scope, that might change before 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)));
}
Run Code Online (Sandbox Code Playgroud)