2

我有一些简单的 jquery 代码,我用它来动态而不是手动创建这个页面。这是我的代码

环形

for ( var i = 0; i < links.length; i++ ) {
    $("#programs").append(
        $("li")
        .html("div")
        .html("a", {
            href: links[i] + ".exe"
        })
        .html("img", {
            src: icons[i]
        })
        .html("p")
        .html(captions[i])
    );
}

数组的声明

var links = ["pictureVeiwer","maze","firefoxPrank"];

var icons = ["firefox-icon.gif","maze.jpg","imageVeiwer.jpg"];

var captions = ["Cute Firfox prank","Cool maze","Program to veiw pictures... kinda useless in 2013"];

我假设我的语法有点偏离,我之前使用过类似的代码,但没有循环使用。我做错了什么,我该怎么做?

小提琴

4

3 回答 3

2

$("li")选择li页面上的所有元素,实际上你并没有创建新元素,它应该是:

$("<li/>");

或者:

$("<li></li>");

此外,您正在链接.html()覆盖以前内容的方法,我建议单独创建元素,如下所示:

for (var i = 0; i < links.length; i++) {
    var $li = $("<li/>"),
        $a = $("<a/>", { href: links[i] + ".exe", text: 'whatever' }),
        $img = $('<img/>', { src: icons[i] });
        $div = $('<div/>').append($a).append($img);

    $li.append($div).appendTo('#programs');  
      // |          |
      // |          ---- append the `li` element to #programs            
      // |           
      // ---- append to the `li` element
}

如果您要动态生成许多元素,您可以考虑使用模板库,如HandlebarsEJSMustache

于 2013-09-29T22:41:24.363 回答
1

我想我在这里工作了。有点冗长,但也更清楚:

for ( var i = 0; i < links.length; i++ ) {
    // Each list item will contain a div
    var $li = $("<li/>")

    // Each div will have a link, and that link will have an image and a caption
    var $div = $("<div/>");

    // Give the link its image
    var $a = $("<a/>", {
        href: links[i] + ".exe"
    });
    var $img = $("<img/>", {
        src: icons[i]
    });
    $a.append($img);

    // Give the link its caption
    $p = $("<p/>");
    $p.html(captions[i]);
    $a.append($p);

    // Give the div its link
    $div.append($a);

    // Give the list item its div
    $li.append($div);

    // Add the list item to the list
    $("#programs").append($li);
}

小提琴 (您需要在自己的网站上尝试,您的图片可以在其中被引用。)

于 2013-09-29T22:52:55.573 回答
1

您还可以使用模板,例如 Underscore 提供的:

HTML:

<script type="text/template" id="list-template">
    <li>
        <div>
            <a href="<%= href %>"><img src="<%= src %>"></a>
            <p><%= caption %></p>
        </div>
    </li>
</script>

<ul id="programs"></ul>

<script src="http://underscorejs.org/underscore-min.js"></script>

JS:

var $programsList = $('#programs');
var listTemplateHtml = $('#list-template').html();
for ( var i = 0; i < 3; i += 1 ) {
    var li = _.template(listTemplateHtml, {
        href: links[i] + ".exe",
        src: icons[i],
        captions: captions[i]
    });
    $programsList.append(li);
}

这将更容易和更易于维护,并且可能也会产生更好的性能。

于 2013-09-29T23:09:38.030 回答