我正在尝试将元素的 id
传递给 storePair
$("#someid").click(storePair($(this).val(),$(this).attr("id"));
使用$(this)
不起作用。没有值(value)。
另一个stackoverflow post建议我使用匿名函数作为 StorePair(val,id) 的包装器,即
$("#someid").click(function(){storePair($(this).val(),$(this).attr("id")});
这似乎有点迂回...有没有办法调用StorePair
并传递值和id而不使用anon函数?
最佳答案
您可以在 storePair
函数内部使用 this
来获取您想要的内容,如下所示:
function storePair() {
var val = $(this).val();
var id = this.id;
//do stuff
}
然后像这样绑定(bind)它:
$("#someid").click(storePair);
或者,使用您已有的匿名函数,无论是否迂回,这就是它的工作方式:)
关于javascript - jQuery - 将 id 元素传递给非匿名回调函数而不使用匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3462880/