Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

javascript - passing array values into a function

In the script below, the console.log is returning the correct values, and both alerts fire. However, the value is coming up undefined.

Any ideas what I'm doing wrong?

jQuery(document).ready(function(){

    jQuery("#customfield_21070").attr('style','width:60px');
    jQuery("#customfield_21070").attr('disabled','disabled');

    var customfields = [
    '#customfield_11070',
    '#customfield_11071',
    '#customfield_20071',
    '#customfield_20072',   
    '#customfield_20073',
    '#customfield_20074',
    ];

    for(var i=0, len=customfields.length; i<len; i++) {
        console.log(customfields[i]);
        jQuery(customfields[i]).keyup(function(){
            alert('calculate');//FIRES
            calculateSum();
        });
    }


    function calculateSum() {

        var sum = 0;

        alert('value: ' + this.value);//UNDEFINED

        if(!isNaN(this.value) && this.value.length!=0 && this.id !== "customfield_21070") {
            sum += parseFloat(this.value);
        }

        jQuery("#customfield_21070").val(sum.toFixed(2));
    }

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Function.prototype.call():

Calls a function with a given this value and arguments provided individually.

Its first parameter is thisArg:

The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.

So, pass this from your handler function to calculateSum like so:

jQuery(customfields[i]).keyup(function(){
    calculateSum.call(this);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...