jQuery使用for循环附加多个克隆的DOM对象

时间:2015-04-24 02:11:49

标签: javascript jquery json

我正在尝试制作一个简单的购物车,使用JSON文件从另一个页面中提取购物车对象。但是,当我开始将克隆的DOM对象附加到product-list div时,它只会附加循环中的最后一个对象,基本上会在最后一次迭代之前覆盖任何对象。

pyg = 'ay'
print "To translate type A SINGLE word or name!"
while True:
    original = raw_input("Type word Here:")

    # Validate the input here. If it's valid, 
    # do the translation.
    if original and original.isalpha():  
        word = original.lower()
        first = word[0]
        new_word = word[1:] + first + pyg
        print "Translating 1 moment..."
        print "Translated view below!"
        print new_word
    else:
        # Tell the user if his input is invalid. 
        print "Your input was stupid. No translation 4 u."

    # Ask the user if he wants to start over
    if raw_input ("Do you want to start over?").lower()[0] != 'y': 
        break

# Give em something to remember you by
print "Made by: Tobias Balentine"

我使用.append和.appendTo尝试了几种不同的变体而没有运气。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

您应该在循环内创建另一个克隆副本 我们的想法是创建元素的“原型”,然后为循环中的每个项目创建该原型的副本:

    // grab a clone of the aside
    $clone= $('.cart-selection').clone();

    //loop through and append a clone with modified JSON information for each item in the cart array
    for(i=0; i<item.length; i++){

        // create a copy of the clone
        $copy = $clone.clone();  

        console.log(i);
        $('h2', $copy).html(item[i].name);
        $('img', $copy).attr("src", item[i].url);
        $copy.appendTo($('product-list'));
    }      

答案 1 :(得分:0)

我猜product-list是一个类名或ID?

$copy.appendTo($('product-list')); <--

如果是这样,您可能需要使用 .product-list #production-list

答案 2 :(得分:0)

您需要在循环中创建克隆,否则您将只创建目标元素的一个克隆,而您只是在循环中更改其内容

$('document').ready(function () {
    var cartArray = JSON.parse(localStorage.getItem("cart"));
    console.log(cartArray);
    parseData(cartArray);
})

function parseData(item) {
    //loop through and append a clone with modified JSON information for each item in the cart array
    for (i = 0; i < item.length; i++) {

        // grab a clone of the aside, need to do in the loop because for each item in the loop we need a new element
        //also should clone only the first instance of the cart-selection else in each iteration you will get multiple elements
        var $copy = $('.cart-selection').eq(0).clone();

        console.log(i);
        $('h2', $copy).html(item[i].name);
        $('img', $copy).attr("src", item[i].url);
        //need to fix the selector here, may be you need a class selector if product-list is a class
        $copy.appendTo($('.product-list'));
    }
}

演示:Fiddle