使用Javascript动态设置onKeyUp属性

时间:2013-12-16 16:26:30

标签: javascript html

我正在编写JS code来计算数字输入的运行总数。我遇到的问题是,对于我的实际项目,我无法直接更改HTML,因为它是从脚本程序生成的。但我可以用JS来操纵它。

到目前为止,我已经添加了一个可以显示输入总和的div。但这仅在输入具有onKeyUp()属性时才有效。对于生成的HTML,情况并非如此,因此我需要编写一个JS script来添加它。这是我到目前为止所做的:

<html>
<head>
<script>
    //try to set an onKeyUp attribute to the elements.
    var number1 = document.getElementById("_Q0_Q0_Q0");
    number1.onkeyup = function(){ return summer()};

    var number2 = document.getElementById("_Q0_Q0_Q1");
    number2.onkeyup = function(){ return summer()};

    var number3 = document.getElementById("_Q0_Q0_Q2");
    number3.onkeyup = function(){ return summer()};

    function summer() {
        var count = 0; //start with nothing
        var num1 = (parseFloat(document.getElementById("_Q0_Q0_Q0").value)) || 0; //if there aren't any numbers, add nothing
        var num2 = (parseFloat(document.getElementById("_Q0_Q0_Q1").value)) || 0;
        var num3 = (parseFloat(document.getElementById("_Q0_Q0_Q2").value)) || 0;
        count = num1+num2+num3; //sum them up
        if (!document.getElementById("output")) { //check to see if there is a div with the output already, if not create one.
        var newDiv = document.createElement('div');
        newDiv.setAttribute('id', 'output');
        var gutterDiv = document.getElementById("right_gutter")
        gutterDiv.appendChild(newDiv);
        };
        document.getElementById("output").innerHTML = "Your running total = "+count
}; //show output
</script>
</head>
<body>
<input type="text" id="_Q0_Q0_Q0" name="number" />
<input type="text" id="_Q0_Q0_Q1" name="number" />
<input type="text" id="_Q0_Q0_Q2" name="number" />
<div id='right_gutter'>
<button type="button" onclick="summer()">Clicking here adds your input to the "count" variable</button> //two purposes of this. 1) Acts as a placeholder for where the output should end up. 2) Shows that the summing function works.
</div>
<br>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

不确定是否正确但不需要这么多代码。

window.onload=function(){
 function sum(){
  result.textContent="Your running total = "+
  ((form.a.value*1)+(form.b.value*1)+(form.c.value*1));
 }
 var form=document.forms[0],result=document.getElementById('result');
 form.addEventListener('keyup',sum,false);
}

HTML

<form><input name="a"><input name="b"><input name="c"></form>
<div id="result"></div>

例如

http://jsfiddle.net/cyLaF/