jQuery点击函数传递参数

jQuery click-function passing parameters

本文关键字:参数 函数 jQuery      更新时间:2023-09-26

我想为数组中的所有元素分配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),显然这不起作用,即myboxunknown内的功能。我想我"有点"理解为什么不能这样做,但怎么才能做到呢?

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