简体   繁体   中英

Function parameter not getting updated inside click event

Q: Function parameter not getting updated inside click event

**Event.js**

// main click event to call
$(document).on('click', '.start', function(){
    root.ajax({
        url: 'location'
    }, function( response ){
        root.update( response );
    })
});

**Content.js**

var flag = false;
root.update = function( response ){ 
    if(!flag){
        // event assignment for new created button
        $(document).on('click', '.innerStart', function(){
            // first time prints okay but after printing old value always
            // response is not getting updated
            console.log( response );
        });
        flag = true;
    }
}

Basically, the response variable is passed in the first time. You set the click event handler, which logs the response, and you never set the click handler again.

That response variable is never changed - the one that was set in the original click handler is always used, because that's the value you passed in. Instead, you could try set it as a variable, like:

**Event.js**
var response;
// main click event to call
$(document).on('click', '.start', function(){
    root.ajax({
        url: 'location'
    }, function( responseValue ){

        root.update( responseValue );
    })
});

**Content.js**

var flag = false;
root.update = function( responseValue ){    
    response = responseValue;
    if(!flag){
        // event assignment for new created button
        $(document).on('click', '.innerStart', function(){
            // first time prints okay but after printing old value always
            // response is not getting updated
            console.log( response );
        });
        flag = true;
    }
}

看起来flag变量设置为true,这使更新运行一次。

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