2

i have some simple jquery code which im using to create this page dynamically instead of manually. here is my code

loop

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

declarations of arrays

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"];

I assume my syntax is a bit off, I have used similar code before but not in a loop. What am I doing wrong and how should I do this?

fiddle.

3 Answers 3

2

$("li") selects all the li elements on the page, actually you don't create new elements, it should be:

$("<li/>");

or:

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

Also you are chaining .html() methods which overwrites previous contents, I would suggest creating elements separately, something like this:

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
}

If you are generating many elements dynamically you can consider using a templating library like Handlebars, EJS or Mustache.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the help so far but i still get this - jsfiddle.net/mendelthecoder/zwhgw/3 - it adds the html outside the elements
@tryingToGetProgrammingStraight .append() methods doesn't return the appended element, it returns the current collection, that's why I have suggested creating the elements separately, what are you currently is doing is writing spaghetti-like/unmanageable code (sorry) which produces unexpected results.
can you write it with a "img" in there?
1

I think I got it working here. A little verbose, but also clearer:

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

Fiddle (You will need to try it on your own site, where your images can be referenced.)

7 Comments

output is this <li> <div> <a href="firefoxPrank.exe"> <img> </a> <p>Program to veiw pictures... kinda useless in 2013</p> </div> </li> (1) p outside of a (2) no src in img
fixed problem (1) - jsfiddle.net/mendelthecoder/zwhgw/6 i will accept if you can fix the src problem as well
found and fixed (2) - jsfiddle.net/mendelthecoder/zwhgw/8 - missing $( before img (and a closing ))
Whoops, I missed that. Glad you caught it. I'll fix my answer for the future generations.
Revision 8 (jsfiddle.net/mendelthecoder/zwhgw/8) looks like it would work. Is something not working on borisute.com/geshem/2013/mkeller/programs.html?
|
1

You could also use templating, like Underscore provides:

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

This would be much easier and more maintainable, and probably yield better performance, too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.