简体   繁体   English

如何在jQuery中将“ X”数量的LI添加到UL中

[英]How to add “X” amount of LI to a UL in jQuery

I'm using jQuery; 我正在使用jQuery; I need to be able to append multiple LI's based on a data attribute. 我需要能够基于数据属性附加多个LI。 My html looks like this: 我的html看起来像这样:

<div class="col">
     <ul class="wonda" data-tick="2"></ul>
     <ul class="panary" data-tick="5"></ul>
</div>

<div class="col">
     <ul class="wonda" data-tick="3"></ul>
     <ul class="panary" data-tick="4"></ul>
</div>

After the script runs it would spit out HTML that looks like this: 脚本运行后,将吐出如下所示的HTML:

<div class="col">
     <ul class="wonda" data-tick="2">
          <li></li>
          <li></li>
     </ul>
     <ul class="panary" data-tick="3">
          <li></li>
          <li></li>
          <li></li>
     </ul>
</div>

<div class="col">
     <ul class="wonda" data-tick="1">
          <li></li>
     </ul>
     <ul class="panary" data-tick="2">
          <li></li>
          <li></li>
     </ul>
</div>

I've tried using append with the data attribute but am getting nowhere. 我尝试将append与data属性一起使用,但是却无济于事。 Is there a better way to do this or does anyone have any ideas? 有没有更好的方法可以做到这一点,或者有人有什么想法吗?

Something like this will work just get the attr data-tick and do a loop creating the elements 这样的事情将起作用,只需要获取attr数据标记并循环创建元素

 $("ul").each(function(){
      var li = parseInt($(this).attr("data-tick"))
      for(i = 0; i < li; i++){
        //Create an li and append it to this = ul element
        $("<li/>").appendTo(this)
       }
   })

Fiddle 小提琴

Something like this should work, without need to modify your HTML: 这样的事情应该可以工作,而无需修改HTML:

function appendToUl(){
    $('.col').find('ul').each(function(){
        var $self = $(this),
            len = $self.data('tick'); // no need to parseInt, .data() autocasts

        for(var i = 0; i < len; i++){
            $self.empty().append('<li/>');
        }
    });
}

Then you call the function when you need to. 然后在需要时调用该函数。 The .empty() piece is if you want to call the function multiple times as like a reset function ... if you only call it once, you can remove it. .empty()件是如果您要像重设功能一样多次调用该功能……如果只调用一次,则可以将其删除。

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

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