将jQuery值一起添加

时间:2013-12-18 16:35:56

标签: 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>

我只是得到字符串'total calculation'而不是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 个答案:

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