jQuery insertAt
我正在尝试使用jQuery将li元素插入到ul元素的特定索引中。 我似乎只能在列表的末尾插入一个元素。 我是jQuery的新手,所以我可能没有正确思考。
尝试这样的事情:
$("#thelist li").eq(3).after("A new item ");
使用eq
函数,您可以获取检索到的元素的特定索引…然后,在其后插入新的列表项。
在上面的函数中,我在第4位插入一个新项目(索引3)。
有关jQuery Docsfunction的更多信息
一个简单的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); } }); }
假设我们有以下HTML:
- A
然后在索引0 $('
').insertAt(0, $('#items'))插入一个项目$('
').insertAt(0, $('#items'))将导致
- C
- A
插入另一个项目,这次是索引1 $('
').insertAt(1, $('#items'))得出
- C
- B
- A
免责声明:输入参数没有error handling。 如果index
为负数或大于子项的长度,或者如果index
不是数字,则行为或多或少未定义。 如果$parent
不是jQuery对象, insertAt
将失败。
与Dreas的答案类似,但略有不同,可能更有效:
$("#thelist li:eq(2)").after("new item ");
或者另一种方式:
$("new item ").insertAfter("#thelist li:eq(2)");
尝试使用此方法..这是在元素中插入文本的最简单方法。
$('#test').append();