在使用javascript再次声明变量之前清除或删除变量

时间:2012-07-18 04:09:05

标签: javascript

我对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>

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

1 个答案:

答案 0 :(得分: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);
}