如何访问计算器的p标签值

时间:2014-04-08 16:38:05

标签: javascript jquery html

我想访问两个p标签'内容并将它们添加到总数中。

这是html:

   <div id="carresult"><p id="caranswer" class="answer"></p><div class="result"> tons       CO<sub>2</sub></div> </div>

  <div id="pubresult"><p  id="pubresults" class="answer"> </p><div class="result"> tons CO<sub>2</sub></div></div>

  <button type="button" id="groundbut">Add to total</button>
    <div id="ground"><p id="groundtotal" class="answer"></p><div class="result"> tons CO<sub>2</sub></div></div>

我想添加&#34; caranswer&#34;和&#34; pubresults&#34;并在&#34; groundtotal&#34;

显示总数

如何从p标签获取数值 javascript:这是错误的

        $("#groundbut").click(function(){

            $("#groundtotal").html($("#caranswer").text()+$("#pubresults").text());
        });

6 个答案:

答案 0 :(得分:3)

你实际上非常接近,你错过了parseInt()

htmlvalue是一个字符串,两个字符串不加(如数学)但是concat:

'123' + '123' = '123123' (type is string)
parseInt('123') + parseInt('123') = 246 (type is integer)

在您的代码中:

$("#groundtotal").html( parseInt($("#caranswer").text()) + parseInt($("#pubresults").text()) );

要完成答案,如果您在严格模式下工作,则需要定义您在10位数系统中工作(因为binairy为2):

parseInt('123', 10);

答案 1 :(得分:1)

变化:

$("#groundtotal").html($("#caranswer").text()+$("#pubresults").text());

$("#groundtotal").html( parseFloat($("#caranswer").text()) + parseFloat($("#pubresults").text()) );

答案 2 :(得分:0)

要将字符串(例如段落的文本)解析为数字,请使用parseInt()。这将返回一个数字,在添加到另一个数字时行为正确。

查看MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

答案 3 :(得分:0)

假设您有jQuery,请尝试:

$("#groundbut").click(function(){    


    $("#groundtotal").html(parseFloat($("#caranswer").text())+parseFloat($("#pubresults").text())); 
});

答案 4 :(得分:0)

$("#groundbut").click(function(){
     $("#groundtotal").html(parseInt($("#caranswer").text())+parseInt($("#pubresults").text()));
}); 

http://jsfiddle.net/SEzn3/

答案 5 :(得分:0)

只要您添加类结果并且将使用p标记

,这个将使用更多输入
$("#groundbut").click(function(){
var sum = 0;
 $("p.answer").each(function(i, item){
     var text = $(item).text();       
     if (text!= '')
     {
      sum+=parseInt(text);
     }
    });
 $('#groundtotal').text(sum);
});
相关问题