jQuery点击函数传递参数
jQuery click-function passing parameters
我想为数组中的所有元素分配jQuery click-function。但此外,我需要从点击功能内访问数组。希望源代码能让它更清晰:
for (var i=0; i<mybox.myarray.length; i++) {
mybox.myarray[i].jqelem.click(function(event, mybox) {
event.preventDefault();
doStuffWithParameter(mybox);
});
}
// mybox is a JavaScript object (not jQuery-element!), myarray is an array, jqelem is a jQueryelement ala $("div.myclass");
问题似乎是与function(event, mybox)
,显然这不起作用,即mybox
是unknown
内的功能。我想我"有点"理解为什么不能这样做,但怎么才能做到呢?
PS:我这样做基本上是为了节省我手动输入所有数组元素
删除(无用的)第二个回调函数参数mybox
如果mybox
在外部块的作用域中,它也会在内部回调函数的作用域中!
如果你需要知道回调中i
的适当值,那么你可以做事件注册时间绑定:
for (var i=0; i<mybox.myarray.length; i++) {
mybox.myarray[i].jqelem.click({i: i}, function(event) {
// use "event.data.i" to access i's value
var my_i = event.data.i;
});
}
映射{i : i}
对应于jQuery .click()
文档中的eventData
参数
当您的click处理程序被调用时,第一个参数是事件数据。jQuery不传递第二个参数。
更新:使用闭包获取mybox
对象(注意我删除了第二个参数)
for (var i=0; i<mybox.myarray.length; i++) {
mybox.myarray[i].jqelem.click(function(event) {
event.preventDefault();
// here's the trick to get the correct i
(function(item) {
return function() {
doStuffWithParameter(mybox.myarray[item]);
};
})(i);
// you can access any object from parent scope here
// (except i, to get to right i, you need another trick),
// effectively creating a closure
// e.g. doOtherStuff(myarray)
});
}
在这里阅读更多关于闭包的信息:http://jibbering.com/faq/notes/closures/
这里:JavaScript闭包是如何工作的?
可以借助jquery的数据属性
for (var i=0; i<mybox.myarray.length; i++) {
mybox.myarray[i].jqelem.data("arrayIndex", i).click(function(event) {
event.preventDefault();
doStuffWithParameter(mybox.myarray[$(this).data("arrayIndex")]);
});
}
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- AngularJS:我可以跳过函数参数回调吗
- 函数未将值作为参数传递
- JS:检查URL中的参数,然后迭代一个参数为var的函数
- 为什么不'我们在javascript中使用函数参数的数据类型
- 你好,这是测试用例,我必须在函数中传递n个参数
- JavaScript - 多参数函数,它是多个图像库的字符串
- 如何从两个参数函数返回随机整数
- 以无点风格在Ramda中编写一个无参数函数
- JS:将单参数函数转换为可链接函数
- 正则表达式类似于Javascript中的参数函数
- 将 $' 值传递给替换的关联参数函数
- "这个“;在参数函数中
- 如何向jquery插件发送参数函数
- 将参数函数Node.js从一个js传递到另一个js
- 如何在javascript参数函数中传递PHP post方法字符串
- 装饰 Javascript Promise.then 以便参数函数接收附加参数
- 正在分析setInterval ID'是的's参数函数
- 如何根据一个参数函数计算年龄
- 对象参数/函数和/或三元运算符混淆