简体   繁体   中英

jQuery: click() executes instead of binding

I'm trying to bind a click event to a function; this happens into a REST get request :

$.get(Constants.webServices.rest.get.pointings(),params,function(data){
    var json = eval(data);
    for(var i=0; i<json.length;i++){
        [...]
        $('a').click(__applyPointing(json[i],originalParams))
        [...]
    }
}

But instead of simply binding, this code executes the function, which is for the moment:

__applyPointing: function(item,originalParams){
    console.log('applyPointing');
    console.log(item);
}

I also tried with bind('click') and on('click'), same result. My js debugger seems useless with an asynchronous request. Please advise.

try to change

$(a).click(__applyPointing(json[i],originalParams))

in

(function(i) {
    $(a).click(function() { __applyPointing(json[i],originalParams) })
}(i))

it's useful wrap the binding into a closure so json[i] is properly passed

Edit: please note that you wrote $(a) and maybe you may want to write $('a')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM