jQuery bind inside a for loop variable scope

帅比萌擦擦* 提交于 2019-12-12 04:59:46

问题


I know this question has been asked many times but I haven't been able to resolve from what I found on Stack O. Here is my code

for(var i=0; i<retrievedSearchesListLength; i++){
retrievedSearchesListProv = retrievedSearchesList[i].searchId;
retrievedSearchesListType = retrievedSearchesList[i].searchParameters;

    function getEventHandlerFunction(a){
    $J.cookies.set('ps_clickedsearch',a);
}

 $J('#submitSearch'+i).bind('click',getEventHandlerFunction(retrievedSearchesListType));
}

Everytime the resulting value is the last for loop value. How do I keep scope so that the link clicked results in the correct value?

I need the correct retrievedSearchesListType to reflect when the link is clicked.

Thanks in advance


回答1:


You need to return the callback method from getEventHandlerFunction

for(var i=0; i<retrievedSearchesListLength; i++){
    retrievedSearchesListProv = retrievedSearchesList[i].searchId;
    retrievedSearchesListType = retrievedSearchesList[i].searchParameters;

    function getEventHandlerFunction(a){
        return function(){
            $J.cookies.set('ps_clickedsearch',a);
        }
    }

    $J('#submitSearch'+i).bind('click',getEventHandlerFunction(retrievedSearchesListType));
}


来源:https://stackoverflow.com/questions/16683343/jquery-bind-inside-a-for-loop-variable-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!