javascript 在Javascript中按下按钮时将项目添加到列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26069477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding items to a list when a button is pressed in Javascript
提问by Johan Karlsson
I am creating a page that has an unordered list of items with the id "faves", a text box with the id "add", and a button with the id "btnAdd". By default the list contains 3 items, but the user is supposed to be able to enter text into the text box, click the button, and whatever they typed into the text box should be added to the list. I can't seem to figure out how to get the text entered to display in the list when the button is clicked.
我正在创建一个页面,其中包含一个无序列表的项目,id 为“faves”,一个文本框的 id 为“add”,一个按钮的 id 为“btnAdd”。默认情况下,列表包含 3 个项目,但用户应该能够在文本框中输入文本,单击按钮,并且应该将他们在文本框中键入的任何内容添加到列表中。我似乎无法弄清楚如何在单击按钮时让输入的文本显示在列表中。
Here is my HTML, this also includes the CSS and Javascript:
这是我的 HTML,这也包括 CSS 和 Javascript:
<html>
<head>
<title>Project 1 Tanner Taylor</title>
<h1>Project 1 Tanner Taylor</title>
<style type="text/css">
#clickMe {
background-color: blue;
border: 2px double black;
font-size: larger;
}
@media (max-width: 299px) {
#faves {
color: red;
}
}
@media (max-width: 500px) and (min-width: 300px) {
#faves {
color: blue;
}
}
@media (min-width: 501px) {
#faves {
display: none;
}
}
</style>
<script type = "text/javascript">
function clickMe() {
document.getElementById("clickMe").innerHTML="Ouch!";
}
</script>
</head>
<body>
<div id="clickMe" onclick="clickMe()">
Click Me!
</div>
<div>
<ul id="faves">
<li>Video Games</li>
<li>Food</li>
<li>Sleeping</li>
</ul>
<input type="text" id="add" size ="50"/>
<input type="button" id="btnAdd" value="Add" onclick=/>
</div>
</body>
</html>
Would anybody be willing to point me in the right direction?
有人愿意为我指出正确的方向吗?
回答by Johan Karlsson
Try this:
试试这个:
<script>
function addItem(){
var li = document.createElement("LI");
var input = document.getElementById("add");
li.innerHTML = input.value;
input.value = "";
document.getElementById("faves").appendChild(li);
}
</script>
<input type="button" id="btnAdd" value="Add" onclick="addItem()">