<div id="test"><h2>test</h2></div>
var obj = [
{num:"1", txt:"text of 1"},
{num:"2", txt:"text of 2"},
{num:"3", txt:"text of 3"},
{num:"4", txt:"text of 4"},
{num:"5", txt:"text of 5"},
];
$.each(obj, function (i, value) {
$('#test h2').after(obj[i].txt + "<br>");
});
输出总是颠倒过来:
text of 5
text of 4
text of 3
text of 2
text of 1
我试图这样做,但它不起作用 - 结果是一样的:
$($(obj).get().reverse()).each(function (i, value) {
$('#test h2').after(obj[i].txt + "<br>");
});
我想要的是按照逻辑顺序输出,从1到5而不是从5到1,我怎么能实现这个呢?
答案 0 :(得分:0)
由于.after()
在指定元素之后插入元素,即h2
,因此您将获得结果。
你非常接近,只需要reverse()
obj
对象
$.each(obj.reverse(), function(i, value) {
$('#test h2').after(obj[i].txt + "<br>");
});
var obj = [{
num: "1",
txt: "text of 1"
}, {
num: "2",
txt: "text of 2"
}, {
num: "3",
txt: "text of 3"
}, {
num: "4",
txt: "text of 4"
}, {
num: "5",
txt: "text of 5"
}, ];
$.each(obj.reverse(), function(i, value) {
$('#test h2').after(obj[i].txt + "<br>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h2>test</h2>
</div>
您可以将.append()
元素用于父test
div。
$('#test').append(obj[i].txt + "<br>");
var obj = [{
num: "1",
txt: "text of 1"
}, {
num: "2",
txt: "text of 2"
}, {
num: "3",
txt: "text of 3"
}, {
num: "4",
txt: "text of 4"
}, {
num: "5",
txt: "text of 5"
}, ];
$.each(obj, function(i, value) {
$('#test').append(obj[i].txt + "<br>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h2>test</h2>
</div>
答案 1 :(得分:0)
由于您使用的是after
,因此每当您在h2
之后立即附加值时。所以请改用append。
var obj = [
{num:"1", txt:"text of 1"},
{num:"2", txt:"text of 2"},
{num:"3", txt:"text of 3"},
{num:"4", txt:"text of 4"},
{num:"5", txt:"text of 5"},
];
$.each(obj, function (i, value) {
$('#test').append(obj[i].txt + "<br>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"><h2>test</h2></div>
答案 2 :(得分:0)
它真的帮助你
$($(obj).get().sort()).each(function (i, value) {
$('#test h2').after(obj[i].txt + "<br>");
});