2

I have many functions for calculating some stats , and i need to recheck the value's every time but that is extra code and make's it harder to read , can i store the variable assignment in another function:

function MC () {
var check=document.getElementById('check').checked;

var ea=Number(document.form.ea.value),
    ed=Number(document.form.ed.value),
    pa=Number(document.form.pa.value),
    pd=Number(document.form.pd.value);

var hpSum = 0,spSum=0,eaSum=0,edSum=0,pdSum=0,paSum=0;

if(check){
    eaSum = ea + 11;
    edSum = ed + 17;
    pdSum = pd + 17;
    paSum = pa + 11;
} else {
    eaSum = ea - 11;
    edSum = ed - 17;
    pdSum = pd - 17;
    paSum = pa - 11;
}

    document.form.ea.value=eaSum;
    document.form.ed.value=edSum;
    document.form.pa.value=paSum;
    document.form.pd.value=pdSum;
};

NOTE:I am speaking for the variables:ea,ed,pa,pd and sum variables.

4

2 回答 2

1

您可以尝试构建参数对象:

function MC() {
  var check = document.getElementById('check').checked,
      keys = {
        "ea":11,
        "ed":17,
        "pd":17,
        "pa":11
      }, i;
  for( i in keys) { if( keys.hasOwnProperty(i)) {
    document.form[i].value = +document.form[i].value + (check ? keys[i] : -keys[i]);
  }}
}

请注意,这+somevarparseFloat(somevar). Number(somevar)与它创建的包装对象不同,如果您稍后添加任何内容,可能会干扰比较。

于 2013-04-13T18:13:05.110 回答
0

我会用你自己的代码,浓缩一点。假设 form 是表单的名称,则需要更多的代码来跟踪哪些输入已更改,而不是读取它们。

function MC () {
    var f= document.form,
    v= document.getElementById('check').checked? [11, 17]:[-11, -17];
    f.ea.value= Number(f.ea.value)+v[0];
    f.ed.value= Number(f.ed.value)+v[1];
    f.pa.value= Number(f.pa.value)+v[0];
    f.pd.value= Number(f.pd.value)+v[1];
}
于 2013-04-13T18:34:52.787 回答