我在数据库表的一行中插入了几个(array
)值和json_encode
的值,现在希望用jquery将它们作为顺序回显。
这是我的PHP代码json_encode
:
[{
"guide": null,
"residence": [{
"name_r": "jack"
}, {
"name_r": "jim"
}, {
"name_r": "sara"
}],
"residence_u": [{
"units": ["hello", "how", "what"],
"extra": ["11", "22", "33"],
"price": ["1,111,111", "2,222,222", "3,333,333"]
}, {
"units": ["fine"],
"extra": ["44"],
"price": ["4,444,444"]
}, {
"units": ["thanks", "good"],
"extra": ["55", "66"],
"price": ["5,555,555", "6,666,666"]
}]
}]
是我在jj调用中的js代码($.ajax({...
):
success: function (data) {
$.each(data[0].residence, function (index, value) {
$('ol#residence_name').append('<li><a href="" class="tool_tip" title="ok">' + value.name_r + '</a><div class="tooltip"></div></li>');
var info = data[0].residence_u[index];
$.each(info.units, function (index, value) {
$('ol#residence_name li .tooltip').append(value + ' & ' + info.extra[index] + ' & ' + info.price[index] + '<br>');
})
});
现在通过上面的js代码,我输出了这个:
jack
hello
&amp;11
&amp;1,111,111
how
&amp;22
&amp;2,222,222
what
&amp;33
&amp;3,333,333,
fine
&amp;44
&amp;4,444,444
thanks
&amp;55
&amp;5,555,555
good
&amp;66
&amp;6,666,666
jim
fine
&amp;44
&amp;4,444,444
thanks
&amp;55
&amp;5,555,555
good
&amp;66
&amp;6,666,666
sara
thanks
&amp;55
&amp;5,555,555
good
&amp;66
&amp;6,666,666
我想要:
jack
hello
&amp;11
&amp;1,111,111
how
&amp;22
&amp;2,222,222
what
&amp;33
&amp;3,333,333,
jim
fine
&amp;44
&amp;4,444,444
sara
thanks
&amp;55
&amp;5,555,555
good
&amp;66
&amp;6,666,666
我该怎么办?
答案 0 :(得分:0)
保持对工具提示元素的引用并将信息附加到它:
var $li = $('<li><a href="" class="tool_tip" title="ok">' + value.name_r + '</a></li>');
var $tooltip = $('<div class="tooltip"></div>').appendTo($li);
var info = data[0].residence_u[index];
$.each(info.units, function (index, value) {
$tooltip.append(value + ' & ' + info.extra[index] + ' & ' + info.price[index] + '<br>');
});
$li.appendTo('#residence_name');
为什么您的代码会产生此结果?
因为$('ol#residence_name li .tooltip')
会在.tooltip
内的每个 li
中选择每个 #residence_name
元素,而不仅仅是当前创造了一个。
答案 1 :(得分:0)
这是一个非常复杂的数据结构 - 我的第一个本能就是将其重新组织成一种不那么大脑融化的格式!但假设结构是固定的,一个漂亮的清晰迭代结构可以帮助解决问题。我在下面提供了一些代码,它们没有做任何事情,但确实提供了一个易于理解的框架。在每个阶段,您需要的变量都可以随时提取使用,这取决于您如何处理数据。未经测试,但应该工作:)
// Declare the variables we're going to use
var i, j; // Iterating variables
var name, unitsArray, extraArray, priceArray; // Outer loop
var unit, extra, price; // Inner loop
// Loop through the people
for( i in data[0].residence ) {
// Assign the outer-loop variables
name = data[0].residence[i].name_r;
unitsArray = data[0].residence_u[i].units;
extraArray = data[0].residence_u[i].extra;
priceArray = data[0].residence_u[i].price;
// Do something here with the name
// For each person, loop through the things they said
for( j in unitsArray ) {
// Assign the inner-loop variables
unit = unitsArray[j];
extra = extraArray[j];
price = priceArray[j];
// Do something here with the 3 inner-loop variables
}
}