使用document.getElementById进行的内场计算不起作用

时间:2014-12-24 15:34:28

标签: javascript input textfield calculator

我在计算输入字段的计算时遇到问题,当用户输入等式时,输入字段会在两个不同的行中发生,字段会更改为答案onChange。这两个部分都是独立工作的,我认为我的问题在于document.getElementByIddocument.getElementById("sA"+row).value = result& document.getElementById("sB"+row).value = resulta

1 个答案:

答案 0 :(得分:0)

基本修正

您的标记和代码中存在许多问题,首先是@ Pointy关于正则表达式的评论。

在下面的更新的工作版本中,我已经注释了内联来解释这些问题:

function Calculate_Value(row) {
    // NOTE: Settle on the regexp approach to use – i.e. /.../ or
    // new RegExp('...').  Also, your operator character class
    // (i.e. [+-\/\*]), contained unnecessary escaping backslashes
    // (i.e. \/\* instead of /*).  Lastly, even using RegExp objects,
    // there is no need to instantiate two variables for the same
    // pattern to use the pattern against subjectA and subjectB.
    var regex = /(\d+)([+-/*])(\d+)/;

    /*
     * infield calculation for Total subjectA
     */

    // NOTE: There is no need for || 0 below.
    var subjectA = document.getElementById("sA" + row).value; // || 0;
    var found = subjectA.match(regex);
    // NOTE: Simplify your logic by checking whether found === null.
    if (found !== null) {
        var operator = found[2];
        // NOTE: Factor out operand parsing from the + operator's
        // logic because it cuts across matchable operators.
        var first = parseInt(found[1], 10);
        var second = parseInt(found[3], 10);
        // NOTE: Explicitly declare the subjectA result variable for
        // consistency.
        var result;

        // NOTE: Support other matchable operators – i.e. -, /, and
        // * in addition to +.
        if (['+'].indexOf(operator) !== -1) {
            result = first + second;
        } else if (['-'].indexOf(operator) !== -1) {
            result = first - second;
        } else if (['/'].indexOf(operator) !== -1) {
            result = first / second;
        } else if (['*'].indexOf(operator) !== -1) {
            result = first * second;
        } else {
            // Execution should not get here unless logic has not been
            // added above for a newly matchable operator (e.g. %); but
            // let's be defensive.
            result = subjectA;
        }

        // NOTE: Factor out setting the element's value because it
        // cuts across all matches.
        document.getElementById("sA" + row).value = result;
    }

    /*
     * infield calculation for Total subjectB
     */

    // NOTE: There is no need for || 0 below.
    var subjectB = document.getElementById("sB" + row).value; // || 0;
    var founda = subjectB.match(regex);
    // NOTE: Simplify your logic by checking whether founda === null.
    if (founda !== null) {
        var operatora = founda[2];
        // NOTE: Factor out operand parsing from the + operator's
        // logic because it cuts across matchable operators.
        var firsta = parseInt(founda[1], 10);
        var seconda = parseInt(founda[3], 10);
        // NOTE: Explicitly declare the subjectB result variable for
        // consistency.
        var resulta;

        // NOTE: Support other matchable operators – i.e. -, /, and
        // * in addition to +.
        if (['+'].indexOf(operatora) !== -1) {
            resulta = firsta + seconda;
        } else if (['-'].indexOf(operatora) !== -1) {
            resulta = firsta - seconda;
        } else if (['/'].indexOf(operatora) !== -1) {
            resulta = firsta / seconda;
        } else if (['*'].indexOf(operatora) !== -1) {
            resulta = firsta * seconda;
        } else {
            // Execution should not get here unless logic has not been
            // added above for a newly matchable operator (e.g. %); but
            // let's be defensive.
            resulta = subjectB;
        }

        // NOTE: Factor out setting the element's value because it
        // cuts across all matches.
        document.getElementById("sB" + row).value = resulta;
    }
}
<table>
  <div class="submit">
    <tr>
      <td align="center">
        <input id="sA1" onchange="Calculate_Value('1');" />
        <!--</div>--> <!-- NOTE: can't close the div mid-td -->
      </td>
      <td align="center">
        <input id="sB1" onchange="Calculate_Value('1');" />
        <!--</div>--> <!-- NOTE: can't close the div mid-td -->
      </td>
    </tr>
  </div> <!-- NOTE: new – to finally close the div -->
</table>

后续注意事项

仅仅因为这个固定版本有效,我不会就此止步。代码中至少有两个明显的气味仍然存在 - 虽然有效:

  1. Calculate_Value subjectAsubjectBCalculate_Value的重复块几乎没有理由:考虑重构Calculate_Value以接受对调用它的输入元素的引用,这将消除很多的重复代码。如果你想要一个尊重Sending $(this) on an onchange on the current element a的{​​{1}}版本,那么另一个问题的答案DRY principle应该会给你一些想法如何作为后续练习。
  2. 如果您没有解决上述残留的气味,请至少重命名您的局部变量以保证清晰。将subjectA附加到与subjectB相关的所有与a相关的本地人 - 相关的逻辑...只是令人困惑(即后缀subjectB实际上是指...... {{1} })。