我想访问两个 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>
我想添加“caranswer”和“pubresults”并在“groundtotal”处显示总数
如何从 p 标签中获取数值 javascript : 这是错误的
$("#groundbut").click(function(){
$("#groundtotal").html($("#caranswer").text()+$("#pubresults").text());
});
最佳答案
你实际上很接近,你错过了parseInt()
.
htmlvalue 是一个字符串,两个字符串不加起来(像数学)而是连接:
'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);
关于javascript - 如何访问计算器的 p 标签值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22943128/