jQuery 在另一个元素之后添加一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2126653/
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
add an element AFTER another?
提问by ajsie
when i use append it add an element WITHIN an element. i want to add an element AFTER an element.
当我使用 append 时,它会在元素内添加一个元素。我想在一个元素之后添加一个元素。
eg.
例如。
<div class="link">
<input class="link" type="text" value="Skriv l?nk" />
<br />
</div>
how do i add an element after 'input' but before 'br'?
如何在“输入”之后但在“br”之前添加元素?
回答by alexn
$("input").after("<p>Hello</p>");
After on jQuery doc: http://api.jquery.com/after/
在 jQuery 文档之后:http: //api.jquery.com/after/
You also have the insertAfter:
您还有insertAfter:
$("<p>Hello</p>").insertAfter("input");
Will work just fine.
会工作得很好。
回答by Alex LE
You should really add an id attribute to your input not only for performance but to be sure that you append only after that specific input:
你真的应该在你的输入中添加一个 id 属性,不仅是为了性能,而且是确保你只在该特定输入之后附加:
<div class="link">
<input id="textBox" class="link" type="text" value="Skriv l?nk" />
<br />
</div>
if using jquery
如果使用 jquery
$("#textBox").after("<p>Hello</p>");
else
别的
var textBox = document.getElementById("textBox");
var element = document.createElement("<p>Hello</p>");
textBox.parentNode.insertBefore(element, textBox.nextSibling);
回答by Max Shawabkeh
回答by Anwar Chandra
// create your element
var $el = $("<div>");
// append after input
$("input.link").after( $el );