简体   繁体   中英

Clone Element and Append to end

I have a HTML template which looks like this:

<div id="amznplist">
    <div id="amznpitem">
        <span>
            <img src="%%Produktbild%%" alt="%%Produkttitel%%"><div id="amzntitle">%%Produkttitel%%</div><div id="amzprice">%%Produktpreis%%</div>
        </span>
    </div>
</div>

What I try to archive is to load the entire html, copy the #amznpitem item, run through my response (data) and populate each li element with the data and add it to the end. What happens is that only one element is added to #amznplist. This is my current code.

            var li = html.find('#amznpitem').clone();
            html.find('#amznpitem').remove();
            var ul = html.find('#amznplist');

            $.each(data, function (index, values) {
                li.find('#amzntitle').text(values['title'][0]);
                li.find('a').attr('href', values['url'][0]);
                li.find('img').attr('src', values['img'][0]);
                li.find('img').attr('alt', values['title'][0]);
                li.find('#amzprice').text(values['lowest_price'][0]);
                $(ul).append(li);

            });
            $('#result').html(html);

You are not iterating over the response data in your loop, you are always accessing the first element - values...[0] . Use the index that you have available in the each function to pass the values from the current iteration

    $.each(data, function (index, values) {
            li.find('#amzntitle').text(values['title'][index]);
            li.find('a').attr('href', values['url'][index]);
            li.find('img').attr('src', values['img'][index]);
            li.find('img').attr('alt', values['title'][index]);
            li.find('#amzprice').text(values['lowest_price'][index]);
            $(ul).append(li);

        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM