简体   繁体   English

克隆元素并追加到结尾

[英]Clone Element and Append to end

I have a HTML template which looks like this: 我有一个看起来像这样的HTML模板:

<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. 我试图存档的是加载整个html,复制#amznpitem项,遍历我的响应(数据),并使用数据填充每个li元素并将其添加到末尾。 What happens is that only one element is added to #amznplist. 发生的是,仅一个元素被添加到#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] 您没有遍历循环中的响应数据,而是始终访问第一个元素- values...[0] . Use the index that you have available in the each function to pass the values from the current iteration 使用each函数中可用的索引来传递当前迭代中的值

    $.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);

        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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