0

我对 javascript 非常陌生,并且正在搞乱一些数学。我目前有:

<input disabled="disabled" type="text" id="backer-prediction-answer" width="100" value="" />

<FORM> 
    <INPUT type="button" value="Apply" name="button1" onclick="apply()">
</FORM>

<script>
var backerPrediction1 = document.getElementById("backer-prediction-1").value;
var backerPrediction2 = document.getElementById("backer-prediction-2").value;
var backerPrediction3 = document.getElementById("backer-prediction-3").value;
var backerPrediction4 = document.getElementById("backer-prediction-4").value;

function apply(){
    var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
    document.getElementById("backer-prediction-answer").value = (backers);
}
</script>

我希望能够点击应用并重新计算。我需要在再次声明之前删除变量吗?如果是这样,我该怎么做?

4

1 回答 1

1

将变量 backerPredictionX 移动到函数内,以便每次应用时都会对它们进行评估()

<script>

function apply(){
    var backerPrediction1 = document.getElementById("backer-prediction-1").value;
    var backerPrediction2 = document.getElementById("backer-prediction-2").value;

    var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
    document.getElementById("backer-prediction-answer").value = (backers);
}
</script>

使用 jquery(代码未验证):

function apply(){
    var backerPrediction1 = $("#backer-prediction-1").val();
    var backerPrediction2 = $("#backer-prediction-2").val();

    var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
    $("#backer-prediction-answer").val(backers);
}
于 2012-07-18T04:17:14.183 回答