如何生成其(文本)内容对应于另一个列表的列表项ID属性的列表项?

时间:2012-04-01 15:45:24

标签: jquery attributes each

我有一个硬编码列表,每个列表项都有一个ID。我想让jQuery在另一个列表中生成列表项,并将每个硬编码列表项的ID属性值设置为其文本内容:

即。硬编码列表:

<ul class="gallery"> 
    <li id="1"></li>
    <li id="2"></li>
    <li id="3"></li>
</ul> 

jQuery生成的列表:

<ul class="galleryNav"> 
    <li>Slide 1</li>
    <li>Slide 2</li>
    <li>Slide 3</li>
</ul> 

我有jQ获取图库项目的数量......

var ListItemCount = $('ul.gallery').children().size('li');

...这就是问题:如何在生成导航列表时(下方)获取jQuery以获取每个列表项的ID?

var ListItemIndex = $('ul.pofo li').attr('id');
var listItem = '<li>Slide #' + ListItemIndex + ' of ' + $('ul.gallery li').length + ' list items!</li>';

这是生成导航列表但是每个内容都是相同的,因为我的blindspot关于var ListItemIndex

$("ul.gallery li").each(function (i) {
    i = i+1;
    $('ul.galleryNav').append(listItem);
});

上述代码的结果会生成列表,但所有列表项的内容都相同,'幻灯片#3 of 3 items'。

非常感谢提前!

SVS

3 个答案:

答案 0 :(得分:2)

我建议:

var newUl = document.createElement('ul'); // It's marginally faster to create elements without jQuery.
newUl.id = 'galleryNav'; // setting the id of the element.
var count = $('.gallery li').length; // retrieving the number of list items
$('body').append(newUl); // appending the created <ul> to the body

$('.gallery li').each(
    function(i){ // iterating through each of the li eleents of the .gallery list
        var li = document.createElement('li'); // creating a new list-element
        // using the i variable returned by the each() function, adding 1 to counter JavaScript's zero-based numbering
        // and appending that created element to the galleryNav
        $(li).text('Slide ' + (i+1) + ' of ' + count).appendTo('#galleryNav');
    }​​​​​​​​​​​​​​​​​​​​​​​​​​​);​

JS Fiddle demo

参考文献:

答案 1 :(得分:2)

我不会将它附加到循环中,而是构造一个字符串并在完成后附加它。它的速度要快得多,然后才能为画廊中的每个li添加它。

var newList = "<ul class='galleryNav'>"; //starting the list

$(".gallery li").each(function(i){ //looping your gallery elements
    newList += "<li>Slide" + this.id || i + "</li>"; //extending the list
});

$("body").append( newList += "</ul>" );  //appending the list to the body or whatever 

演示:

http://jsfiddle.net/meo/yKgSf/

或花哨的版本(因为用JS构造长字符串可能很慢)

var newList = []; // creating a empty array

$(".gallery li").each(function(i){ //looping your gallery list
    newList.push("<li>Slide" + this.id || i + "</li>"); //extending the array
});

$("body").append( "<ul class='galleryNav'>" + newList.join("") + "</ul>" ); //joining the array and append it to the body

演示: http://jsfiddle.net/meo/yKgSf/2/

PS:只有ID作为ID才能在HTML4中使用W3C。这就是为什么当元素上没有ID时我选择使用索引

答案 2 :(得分:1)

以下是 jsFiddle 。代码:

var listItemCount = $('.gallery').children().size('li');

$('.gallery li').each(function() {
    $('.galleryNav').append(
        '<li>Slide #' + $(this).attr('id') + ' of ' 
             + listItemCount + ' list items!</li>');
});

您的代码具有正确的基础知识,您只需要将附加内容移动到将为每个列表项执行的each函数。然后可以使用$(this)访问该项目。