2013-12-18 32 views
0

我想將jQuery元素中的兩個值加在一起,我不明白我在做什麼不正確。這裏是我的代碼:將jQuery值加在一起

$(document).on('pageinit', function() { //init and start function 
    $("#saveHospital").click(function(){ //run function on button click 
     var Hospitalval = $("#Hospital").val(); //assign value from element id #Hospital, which is a slider 
    }); 
    $("#saveICU").click(function(){ //run function on button click 
     var ICUval = $("#ICU").val(); //assign value from element id #Hospital, which is a slider 
     var surgicalProc = parseInt(Hospitalval) + parseInt(ICUval); //parse both strings to integers and add them together 
     $('.P14').html(surgicalProc); //set selector to display the value of the variable 
    }); 

這是我的HTML其中值是要顯示:

<p class="P14">Total calculation</p> 

林剛開字符串「總計算」,而不是surgicalProc的價值。僅供參考如果我將兩個用數字解析的變量替換掉,這個函數就可以工作,所以我知道錯誤在定義中的某處,但我看不到它。

有什麼想法?

這裏是其中的元素定義的HMTL:我認爲你可變量的作用域的問題在這裏處理

滑塊

<input type="range" name="Hospital" id="Hospital" value="60" min="0" max="100" /> 
<input type="range" name="ICU" id="ICU" value="60" min="0" max="100" /> 

按鈕

<a href="#pageThree" id="saveHospital" data-role="button" data-theme="b" data-transition="slide">Submit</a> 
<a href="#pageFour" id="saveICU" data-role="button" data-theme="b" data-transition="slide">Submit</a> 
+1

你能添加HTML,所以我們可以看到其中的值是從哪裏來的? – DMortensen

+0

我添加了html來清晰度 – DataGuy

+0

Robbert的回答我相信是正確的。如果要在同一範圍內的其他函數中使用它,則需要在函數外定義該變量。 – DMortensen

回答

4

Hospitalval被定義在一個函數中,並在另一個函數中調用它。

這可能會爲你工作

var Hospitalval = 0; 
$(document).on('pageinit', function() { //init and start function 

    $("#saveHospital").click(function(){ //run function on button click 
     Hospitalval = $("#Hospital").val(); //assign value from element id #Hospital, which is a slider 
    }); 
    $("#saveICU").click(function(){ //run function on button click 
    var ICUval = $("#ICU").val(); //assign value from element id #Hospital, which is a slider 
    var surgicalProc = parseInt(Hospitalval) + parseInt(ICUval); //parse both strings to integers and add them together 
    $('.P14').html(surgicalProc); //set selector to display the value of the variable 
    });