我想从这个对象中取出物品:
var things = {
"thing1" : "I'm one",
"thing2" : "I'm two",
"thing3" : "I'm three",
}
并将它们添加到此标记中:
<div class="allthings">
<div class="thing1">other content first. </div>
<div class="thing2">other content first. </div>
<div class="thing3">other content first. </div>
</div>
导致:
<div class="thing1">other content first. <p class="added">I'm one</p></div>
... etc.
我不擅长.each()循环。什么是jQuery相当于:
“对于对象中的每个项目,找到与该项目的键匹配的类的div,并将该项目的值附加为”已添加“类的段落。”
答案 0 :(得分:2)
我要做什么:
for (var i in things) $("."+i).append("<p class='added'>"+things[i]+"</p>");
仅限Jquery的解决方案:
$.each(things,function(i,e) {$("."+i).append("<p class='added'>"+e+"</p>");});
答案 1 :(得分:1)
$.each(things, function(k, v){
var sel = '.' + k,
$el = $(sel);
$el.html($el.html() + '<p class="added">' + v + '</p>');
});
答案 2 :(得分:1)
这将有效:
$.each(things, function(key, value) {
$("<p />").addClass("added").text(value).appendTo("." + key);
});
DEMO: http://jsfiddle.net/exEbw/
更新。对于ID,在#
选择器中使用哈希.
字符而不是点appendTo
:
$("<p />").addClass("added").text(value).appendTo("#" + key);
答案 3 :(得分:1)
试试这个。
jQuery.each(things, function(i,j) {
$("." + i).append('<p class="added">'+j+'</p>');
});