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

后端 未结 4 1384
傲寒
傲寒 2020-12-04 10:10

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

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


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 10:35

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

提交回复
热议问题