1

我想从这个对象中取出物品:

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,并将项目的值附加为带有“已添加”类的段落。”

4

4 回答 4

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>");});
于 2012-06-18T20:27:03.817 回答
1

这将起作用:

$.each(things, function(key, value) {
    $("<p />").addClass("added").text(value).appendTo("." + key);
});

演示:http: //jsfiddle.net/exEbw/


更新。对于 ID ,在选择器中使用哈希#字符而不是点:.appendTo

$("<p />").addClass("added").text(value).appendTo("#" + key);

演示:http: //jsfiddle.net/exEbw/1/

于 2012-06-18T20:24:55.827 回答
1

尝试这个。

jQuery.each(things, function(i,j) {
    $("." + i).append('<p class="added">'+j+'</p>');
});
于 2012-06-18T20:29:58.423 回答
1
$.each(things, function(k, v){
    var sel = '.' + k,
        $el = $(sel);
    $el.html($el.html() + '<p class="added">' + v + '</p>');
});

看演示

于 2012-06-18T20:24:02.090 回答