将参数传递给 click() &jQuery 中的 bind() 事件? [英] Passing parameters to click() & bind() event in jQuery?

查看:19
本文介绍了将参数传递给 click() &jQuery 中的 bind() 事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将几个参数传递给 jQuery 中的 click() 事件,我尝试了以下操作,但它不起作用:

I want to pass few parameters to click() event in jQuery, I tried following but it's not working:

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

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

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

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

推荐答案

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

这篇关于将参数传递给 click() &jQuery 中的 bind() 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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