【问题标题】:insert content from object into specific div's with jQuery .each() loop使用 jQuery .each() 循环将对象中的内容插入特定的 div
【发布时间】:2012-06-18 20:20:02
【问题描述】:

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

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

【问题讨论】:

    标签: jquery foreach javascript-objects


    【解决方案1】:

    我会做什么:

    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>");});
    

    【讨论】:

    • 具有更优化的 javascript 实现的信息更丰富的解决方案。但以不太可读的形式呈现。
    【解决方案2】:

    这将起作用:

    $.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/

    【讨论】:

    • 谢谢,对编辑感到抱歉,我意识到我的书面描述中有标记和 id 类..
    • @nathanbweb 无论如何,现在你有两个选择:)
    【解决方案3】:
    $.each(things, function(k, v){
        var sel = '.' + k,
            $el = $(sel);
        $el.html($el.html() + '<p class="added">' + v + '</p>');
    });
    

    See demo

    【讨论】:

    • 顺便说一句,最好使用append() 而不是html(html() + ...)。或者如果你更喜欢html方法,那么这里使用回调函数更可取。
    【解决方案4】:

    试试这个。

    jQuery.each(things, function(i,j) {
        $("." + i).append('<p class="added">'+j+'</p>');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-21
      • 2015-08-03
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      相关资源
      最近更新 更多