jquery追加元素,直到达到一定数量

时间:2021-10-07 01:08:49

I have an <ul> and I want to append <li> elements until they will reach the amount of 10

我有一个

    ,我想追加
  • 元素,直到它们达到10

How is the best practice to do this in jQuery?

在jQuery中执行此操作的最佳实践是什么?

It could be great also if the solution can consider that sometimes I can already have for example 5 <li>, so in this case I only want to append 5 more elements to reach the amount of 10...

如果解决方案可以考虑有时我已经可以拥有例如5

  • ,那也可能很好,所以在这种情况下我只想追加5个元素以达到10 ...

  • 2 个解决方案

    #1


    1  

    You can do it with a while loop like

    您可以使用while循环来完成

    while(!$('li:gt(9)').length){
            $('ul').append('<li></li>');
        }
    

    just use :gt() to see if an eleventh element exists yet or not.

    只需使用:gt()来查看第11个元素是否存在。

    #2


    1  

    Lets just assume that you have a variable that holds the number of li to be appended. For loop is the best choice, you can control the number of iterations.

    让我们假设您有一个变量来保存要追加的li数。 For循环是最佳选择,可以控制迭代次数。

    var counter = 10; // depends on desired count, 
    for (var i = 0; i < counter; i++) {
        if ( !$( '#li_ID' ).length ) // check if li already exist
             $('ul').append('<li></li>')
    }
    

    #1


    1  

    You can do it with a while loop like

    您可以使用while循环来完成

    while(!$('li:gt(9)').length){
            $('ul').append('<li></li>');
        }
    

    just use :gt() to see if an eleventh element exists yet or not.

    只需使用:gt()来查看第11个元素是否存在。

    #2


    1  

    Lets just assume that you have a variable that holds the number of li to be appended. For loop is the best choice, you can control the number of iterations.

    让我们假设您有一个变量来保存要追加的li数。 For循环是最佳选择,可以控制迭代次数。

    var counter = 10; // depends on desired count, 
    for (var i = 0; i < counter; i++) {
        if ( !$( '#li_ID' ).length ) // check if li already exist
             $('ul').append('<li></li>')
    }