我计划将toDos的每个元素添加到列表中,但只显示列表中的最后一个元素。
我知道以下代码行会导致问题,但不明白原因。
$tag_li= $tag_li.text(toDo);
我的代码:
var $organizedByTag=[ { "name":"shopping", "toDos":["Get groceries","HAHA","HEIHEI"]
}, {
"name": "chores",
"toDos": ["Get groceries", "Take Gracie to the park"]
}];
$organizedByTag.forEach(function (Tag) {
var $tag_ul = $(" <ul > ");
var $tag_li=$(" <li > ");
$tag_head=$(" <h3 >").text(Tag.name); Tag.toDos.forEach(function(toDo){ $tag_li= $tag_li.text(toDo);
$tag_ul.append($tag_li);
});
$(".content").append($tag_head); $(".content").append($tag_ul);
});
<div class="content">
<ul>
<li>Get Groceries</li>
<li>Make up some new ToDos</li>
<li>Prep for Monday's class</li>
<li>Answer recruiter emails on Linkedin</li>
<li>Take Gracie to the park</li>
<li>Finish writing book</li>
</ul>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 0 :(得分:0)
var $tag_li = $("<li>");
函数中的 Tag.toDos.forEach(function(toDo) {
。这是因为对于数组中的每个元素都应创建li
。此处只创建了一个li
,而li
的上一个文本被最后一个替换。
var $organizedByTag = [{
"name": "shopping",
"toDos": ["Get groceries", "HAHA", "HEIHEI"]
},
{
"name": "chores",
"toDos": ["Get groceries", "Take Gracie to the park"]
}
];
$organizedByTag.forEach(function(Tag) {
var $tag_ul = $("<ul>");
$tag_head = $("<h3>").text(Tag.name);
Tag.toDos.forEach(function(toDo) {
var $tag_li = $("<li>");
$tag_li = $tag_li.text(toDo);
$tag_ul.append($tag_li);
});
$(".content").append($tag_head);
$(".content").append($tag_ul);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<ul>
<li>Get Groceries</li>
<li>Make up some new ToDos</li>
<li>Prep for Monday's class</li>
<li>Answer recruiter emails on Linkedin</li>
<li>Take Gracie to the park</li>
<li>Finish writing book</li>
</ul>
</div>
&#13;
答案 1 :(得分:0)
您只需创建tag_li
一次,然后再重写其文本并再次将其添加到ul中。您需要为每个项目创建一个新项目。
这应该解决它:
var $organizedByTag = [{
"name": "shopping",
"toDos": ["Get groceries", "HAHA", "HEIHEI"]
},
{
"name": "chores",
"toDos": ["Get groceries", "Take Gracie to the park"]
}
];
$organizedByTag.forEach(function(Tag) {
var $tag_ul = $("<ul>");
$tag_head = $("<h3>").text(Tag.name);
Tag.toDos.forEach(function(toDo) {
var $tag_li = $("<li>");
$tag_li = $tag_li.text(toDo);
$tag_ul.append($tag_li);
});
$(".content").append($tag_head);
$(".content").append($tag_ul);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<ul>
<li>Get Groceries</li>
<li>Make up some new ToDos</li>
<li>Prep for Monday's class</li>
<li>Answer recruiter emails on Linkedin</li>
<li>Take Gracie to the park</li>
<li>Finish writing book</li>
</ul>
</div>
P.S。:变量名称不需要$
。