jQuery insert div as certain index

后端 未结 9 744
眼角桃花
眼角桃花 2020-12-07 19:38

Say I have this:

1
2

bu

9条回答
  •  青春惊慌失措
    2020-12-07 20:25

    I had a similar problem. Unfortunately none of the solutions worked for me. So I coded it this way:

    jQuery.fn.insertAt = function(index, element) {
      var lastIndex = this.children().size();
      if (index < 0) {
        index = Math.max(0, lastIndex + 1 + index);
      }
      this.append(element);
      if (index < lastIndex) {
        this.children().eq(index).before(this.children().last());
      }
      return this;
    }
    

    Examples for the problem:

    $("#controller").insertAt(0, "
    first insert
    "); $("#controller").insertAt(-1, "
    append
    "); $("#controller").insertAt(1, "
    insert at second position
    ");

    Here are some examples taken from my unittests:

    $("
      ").insertAt(0, "
    • 0
    • "); $("
        ").insertAt(0, "
      • 0
      • ").insertAt(1, "
      • 1
      • "); $("
          ").insertAt(-1, "
        • -1
        • "); $("
            ").insertAt(-1, "
          • -1
          • ").insertAt(0, "
          • 0
          • "); $("
              ").insertAt(0, "
            • 0
            • ").insertAt(-1, "
            • -1
            • "); $("
                ").insertAt(-1, "
              • -1
              • ").insertAt(1, "
              • 1
              • "); $("
                  ").insertAt(-1, "
                • -1
                • ").insertAt(99, "
                • 99
                • "); $("
                    ").insertAt(0, "
                  • 0
                  • ").insertAt(2, "
                  • 2
                  • ").insertAt(1, "
                  • 1
                  • "); $("
                      ").insertAt(0, "
                    • 0
                    • ").insertAt(1, "
                    • 1
                    • ").insertAt(-1, "
                    • -1
                    • "); $("
                        ").insertAt(0, "
                      • 0
                      • ").insertAt(1, "
                      • 1
                      • ").insertAt(-2, "
                      • -2
                      • "); $("
                          ").insertAt(0, "
                        • 0
                        • ").insertAt(1, "
                        • 1
                        • ").insertAt(-3, "
                        • -3
                        • "); $("
                            ").insertAt(0, "
                          • 0
                          • ").insertAt(1, "
                          • 1
                          • ").insertAt(-99, "
                          • -99
                          • ");

    Edit: It handles all negative indizes gracefully now.

提交回复
热议问题