开发者

Javascript-list of nested tags

开发者 https://www.devze.com 2023-04-03 07:27 出处:网络
I have to create the following type of HTML structure: <div id=\"dcontent\"> <ul class=\"thm\">

I have to create the following type of HTML structure:

<div id="dcontent">
    <ul class="thm">
        <li><a href="#"><img src="img/theme1.jpg" id="t1" border="none"/></a></li>
        <li><a href="#"><img src="img/theme2.jpg" id="t2" border="none"/></a></li>
        <li><a href="#"><img src="img/theme3.jpg" id="t3" border="none"/></a></li>

I need to create 18 nested images this way so I use the following Javascript loop:

for (var count = 1; count < 19; count++) {
    newLi = document.createElement('li');
    newLi.setAttr开发者_如何学编程ibute('id', 'l' + count);
    newLink = document.createElement('a');
    newLink.setAttribute('href', '#');
    newLink.setAttribute('id', 'a' + count);
    $(newLink).appendTo('#l' + count);
    newImg = document.createElement('img');
    newImg.setAttribute('src', thumbPath + count + '.jpg');
    newImg.setAttribute('id', 't' + count);
    newImg.setAttribute('border', 'none');
    $(newImg).appendTo('#a' + count);
    $(newLi).appendTo('.thm');
}

The code outputs only li nested in ul which is nested in div. Is it better to use jQuery because I read that document.createElement (pure Javascript) is faster method. Any help will be greatly appreciated.


You don't need any jQuery at all.

You can replace the appendTo functions as well, with

var parent = document.getElementById("id");
parent.appendChild(child);


 var $thm = $('.thm');
 for(var count=1; count<19; count++)
 {
    var $li = $('<li><a href="#"><img src="img/theme' + count + '.jpg" id="t' + count + '" border="none"/></a></li>')
    $thm.append($li);
 }


jQuery is a set of abstractions to ease your work with JavaScript. This does mean you will perform extra logic to perform the same task.

You need to find a balance between performance at runtime and the time it takes for you to develop.

0

精彩评论

暂无评论...
验证码 换一张
取 消