jQuery 插入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/391314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:04:55  来源:igfitidea点击:

jQuery insertAt

jquery

提问by ilivewithian

I'm trying to insert an li element into a specific index on a ul element using jQuery. I only seem to be able to insert an element on the end of the list. I am very new to jQuery, so I may just not be thinking properly.

我正在尝试使用 jQuery 将 li 元素插入到 ul 元素的特定索引中。我似乎只能在列表的末尾插入一个元素。我对 jQuery 很陌生,所以我可能没有正确思考。

回答by Andreas Grech

Try something like this:

尝试这样的事情:

$("#thelist li").eq(3).after("<li>A new item</li>");

With the eqfunction, you can get a specific index of the elements retrieved...then, insert the new list item after it.

使用该eq函数,您可以获得检索到的元素的特定索引...然后,在它之后插入新的列表项。

In the above function, I am inserting a new item at position 4 (index 3).

在上面的函数中,我在位置 4(索引 3)插入一个新项目。

More info about the function at the jQuery Docs

有关jQuery Docs 中的函数的更多信息

回答by mrydengren

A simple jQuery plugin (a small test suite) which permits adding an item at any index including 0.

一个简单的 jQuery 插件(一个小型测试套件),它允许在包括 0 在内的任何索引处添加一个项目。

$.fn.insertAt = function(index, $parent) {
    return this.each(function() {
        if (index === 0) {
            $parent.prepend(this);
        } else {
            $parent.children().eq(index - 1).after(this);
        }
    });
}

Assuming we have the following HTML:

假设我们有以下 HTML:

<ul id="items">
    <li>A</li>
</ul>

Then inserting an item at index 0 $('<li>C</li>').insertAt(0, $('#items'))will result in

然后在索引 0 处插入一个项目$('<li>C</li>').insertAt(0, $('#items'))将导致

<ul id="items">
    <li>C</li>
    <li>A</li>
</ul>

Inserting another item, this time at index 1 $('<li>B</li>').insertAt(1, $('#items'))yields

插入另一个项目,这次在索引 1 处$('<li>B</li>').insertAt(1, $('#items'))产生

<ul id="items">
    <li>C</li>
    <li>B</li>
    <li>A</li>
</ul>

Disclaimer:there is no error handling of input parameters. If indexis negative or greater than the length of children or if indexis not a number the behavior is more or less undefined. If $parentis not a jQuery object insertAtwill fail.

免责声明:输入参数没有错误处理。如果index是负数或大于孩子的长度,或者如果index不是数字,则行为或多或少是未定义的。如果$parent不是 jQuery 对象insertAt将失败。

回答by nickf

Similar to Dreas's answer, but slightly different and possibly more efficient:

类似于 Dreas 的答案,但略有不同,可能更有效:

$("#thelist li:eq(2)").after("<li>new item</li>");

Or another way:

或者另一种方式:

$("<li>new item</li>").insertAfter("#thelist li:eq(2)");

回答by Aristotle Ucab

Try to use this method.. it's the simplest way to insert text inside an element..

尝试使用此方法.. 这是在元素内插入文本的最简单方法..

<div id="test"></div>

$('#test').append();