所以,我正在为我的商店制作一个在线程序,我正在尝试添加段落标签以获得总成本。我刚得到 [object HTMLCollection]
<!DOCTYPE html>
<html>
<body>
<h1>Cash Register</h1>
//name and price
<input type="text" id="myText1" value="Name">
<input type="text" id="myText2" value="Price">
<button onclick="add()">Add</button>
<div id="div1">
<h2 id="demo1">
<h2 id="demo2"></h2>
</div>
<script>
function add() {
//my variables
var x = 'Total:'
var y = document.getElementById("myText2").value;
var z = document.getElementById("myText1").value;
//create the paragraphs
var para = document.createElement("h4");
var node = document.createTextNode('_____');
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
var para = document.createElement("h4");
var node = document.createTextNode(z);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
var para = document.createElement("p");
var node = document.createTextNode(y);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
//writes "Total (total)"
var w = document.getElementsByTagName("p");
document.getElementById("demo1").innerHTML = x;
document.getElementById("demo2").innerHTML = w;
}
</script>
</body>
</html>
如果有人能帮忙,那就太好了。这是我的结果:
最佳答案
这是一段新的代码,将//writes total 下面的部分替换为这个。
//writes "Total (total)"
var w = document.getElementsByTagName("p"); // this gets all the P's as an object
// setup a total starting at 0
var total = 0;
for (var i = 0; i < w.length; i++) {
total += parseInt(w[i].innerText); // make the inner text an integer for addition.
}
document.getElementById("demo1").innerHTML = x;
document.getElementById("demo2").innerHTML = total; // replace w with total
您的问题是您正在使用
获取元素集合var w = document.getElementsByTagName("p");
具有“对象”的值。相反,您需要遍历它,然后将值相加。
关于javascript - 需要帮助将段落标签加在一起以达到总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50260069/