将数组值传递给一个函数 [英] passing array values into a function

查看:150
本文介绍了将数组值传递给一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的脚本中,console.log正在返回正确的值,并且两个警报都会触发。然而,价值是未定义的。



任何想法我做错了什么?

  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',
];

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


函数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);

$ b $ j jQuery(#customfield_21070).val(sum.toFixed(2));
}

});


解决方案

使用 Function.prototype.call()


$ b


使用给定的这个值和提供的参数
$ b

它的第一个参数是 thisArg


这个为fun调用提供的值。请注意, this 可能不是
是该方法看到的实际值:如果该方法是
非严格模式代码中的函数,则为null undefined将被替换为
全局对象,原始值将被装箱。


所以,传入<$ c $从你的处理函数到 calculateSum 如下所示:

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


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

});

解决方案

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

这篇关于将数组值传递给一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆