jQuery 在元素之前添加
我有一个像这样的 html 结构/
<li id="1"></li>
<li id="2"></li>
<li id="3"></li>
<li id="comment-box"></li>
现在我想
<li id="4"></li>
在评论框之前添加。
我正在从评论框中提交一份表格,一旦成功,我想在前面添加。
I have a html structure like this/
<li id="1"></li>
<li id="2"></li>
<li id="3"></li>
<li id="comment-box"></li>
now i wanna prepend
<li id="4"></li>
before comment-box.
i am submitting a form from the comment box and once its a success i wanna do the prepend.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 before():
Use before():
这不是更有意义吗?:
或者
这将允许您将其添加到 ul 列表的开头,将其放在列表的末尾,只需使用“append”而不是“prepend”或“appendTo”也可以。
Wouldn't this make more sense?:
or
This would allow you to add it to the beginning of a ul list to put it at the end of the list just use 'append' rather than 'prepend' or 'appendTo' also works.
将顺序 id 附加到元素的情况并不常见,但可能的情况是在未知长度的匹配元素的特定索引处插入。
如果您知道列表中有多少个项目,那么您可以使用 nth-child 或 :eq 直接访问该项目,而无需将标记类名称或 id 连接到 jQuery 选择器中。
$('li:nth-child(3)')
选择第三个而
$('li:eq(3)')< /code> 选择第四个,因为 :eq 是从零开始的。
在你的情况下,我的偏好如下
Here is a fiddle
It is uncommon to have a sequential id attached to elements but a likely case would be inserting at a specific index of a unknown length of matching elements.
If you know how many items are in the list then you can use nth-child or :eq to directly access the item without needing to couple your markup class names or id's into the jQuery selector.
$('li:nth-child(3)')
selects the third<li>
while$('li:eq(3)')
selects the fourth because :eq is zero based.In your case my preference would be the following
Here is a fiddle
如果你严格想使用 .prepend(),以下内容将帮助你:
或者
同样,使用 .eq(),在你掌握主要想法后,这会更优雅。 .eq 允许您引用特定索引。
最后我们得出了最终的简短变体:
If you strictly want to use the .prepend(), the following will help you:
OR
The same, using .eq(), which will be more elegant after you got the main idea. .eq allows you to refer at particular index.
And finally we came to the final short variant: