将数组值传递给一个函数 [英] passing array values into a function
问题描述
任何想法我做错了什么?
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 thatthis
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屋!