我正在使用javascript用户输入内容,并使用它来显示该页面数。基本上,我问用户他们有多少个物品。如果他们说,例如4,我需要问他们下一页上每个项目的名称。然后,在接下来的4页上,他们将每页输入每个项目的值,最后,我将显示项目,值和最终总和的表格。我的问题是:
很抱歉,如果这是一个非常愚蠢的问题,那么这里只是一个困惑的初学者。谢谢!
这是我到目前为止所拥有的:
index.html:
<body>
<h1>Welcome!</h1>
<h2>Ready to track your items?</h2>
<p><button><a href="items.html">Start</a></button></p>
</body>
items.html:
<body>
<h3>How many items do you have?</h3>
<p><input id="numItems"></p>
<script src="main.js"></script>
</body>
main.js:
var numIt = document.getElementById("numItems");
numIt.addEventListener("input", display);
function display(){
var item = parseFloat(numIt.value);
alert("you have " + item+" items");
}
答案 0 :(得分:0)
我不确定100%,但是您需要动态生成N个输入,以使用户填写每个项目的名称。如前所述,打开新文件或创建新的html文件不是最佳解决方案,也无法使用浏览器javascript完成。
因此,为什么不生成输入元素并将其附加到DOM,有关更多信息,请参见DOM w3schools
小例子。
function display(){
var item = parseFloat(numIt.value);
for(var i =0; i<item;i++){
var inpElem = document.createElement("input");
inpElem.setAttribute("name", "item"+i);
inpElem.setAttribute("placeholder", "Input name of the item #"+i);
document.body.appendChild(inpElem);
}
}
比方说用户输入2。它将生成
<input placeholder="Input name of the item #1" name="item1" >
<input placeholder="Input name of the item #2" name="item2" >
也可以清空主体-document.body.innerHTML = ""
答案 1 :(得分:0)
可能您可以使用“页面”(隐藏除一个元素之外的所有元素)
有一个例子,您可以查看一下
const pages = ["page1", "page2", "page3"]
showPage(0)
function hidePages() {
for(const page of pages)
changeElementVisibility(page, false)
}
function showPage(num) {
hidePages()
const pageId = pages[num]
changeElementVisibility(pageId, true)
}
function changeElementVisibility(id, visible) {
document.getElementById(id).style.display = visible ? "" : "none"
}
function secondPageSumbit() {
const itemsCount = document.getElementById("itemsCount").value
document.getElementById("result").innerText = "Items Count: " + itemsCount
}
<head>
<script src="main.js"></script>
</head>
<body>
<div id="page1">
<h1>Welcome!</h1>
<h2>Ready to track your items?</h2>
<p><button onclick="showPage(1)">Start</button></p>
</div>
<div id="page2">
<h3>How many items do you have?</h3>
<p><input id="itemsCount"></p>
<p><button onclick="secondPageSumbit();showPage(2)">Next</button></p>
</div>
<div id="page3">
<h3>Result</h3>
<p id="result"></p>
</div>
</body>