使用 Javascript 将新列表元素添加到无序列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12490439/
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 new list elements to an unordered list with Javascript
提问by Rob
I am trying to add new elements to an unordered list with the following code:
我正在尝试使用以下代码将新元素添加到无序列表中:
The HTML:
HTML:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Javascript</title>
<link rel="stylesheet" href="jsPlay.css" type="text/css" />
<script src="jsPlay.js"></script>
</head>
<body>
<ul id="numberList"></ul>
</body>
</html>
The Javascript:
Javascript:
window.onload = function()
{
//alert("Window is loaded");
var numberList = document.getElementById("numberList");
//for every number between 100 and 200
for(var i = 0; i > 100 && i < 200; i++)
{
if ( i % 17 == 0 && i % 2 == 0) //if number evenly divisible by 17 and 2
{
//create new li element
var newNumberListItem = document.createElement("li");
//create new text node
var numberListValue = document.createTextNode(i);
//add text node to li element
newNumberListItem.appendChild(numberListValue);
//add new list element built in previous steps to unordered list
//called numberList
numberList.appendChild(newNumberListItem);
}
}
}
When I run this in my browser, I just get nothing but white-space. I check in FireBug (on Firefox 15.0.1) to see if there are any errors, but there is nothing noticeable. I think I am not binding something together properly - it seems like such a basic problem but I can't seem to fgure out why the elements aren't being added to the unordered list.
当我在浏览器中运行它时,我只得到空白。我检查了 FireBug(在 Firefox 15.0.1 上)以查看是否有任何错误,但没有什么值得注意的。我想我没有正确地将某些东西绑定在一起 - 这似乎是一个基本问题,但我似乎无法弄清楚为什么元素没有被添加到无序列表中。
I'm sure the commenting in the Javascript code is sufficient, but feel free to ask me questions if it isn't.
我确信 Javascript 代码中的注释足够了,但如果不是,请随时问我问题。
Many thanks for the help :).
非常感谢您的帮助 :)。
回答by grc
Your for loopimmediately fails because i
is not greater than 100. If you try something like this it should work:
你的for 循环立即失败,因为i
它不大于 100。如果你尝试这样的事情,它应该可以工作:
for (var i = 100; i < 200; i++)
Example: http://jsfiddle.net/grc4/gc4X5/1/