所以,我正在为我的商店制作一个在线程序,我正在尝试添加段落标签以获得总成本。我得到[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>
&#13;
如果有人可以提供帮助,那就太好了。这是我的结果:
答案 0 :(得分:1)
这是一个新的代码,用//替换// writ 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");
具有&#34; Object&#34;的值。相反,您需要遍历它,并将值相加。