[英]jQuery: How to append something after one element?
DOM DOM
<div id="a">
<div id="b"></div>
<div>
<p>Insert me after #b</p>
Requirement is insert p tag after '#b', and when the insert operation happened again, only replace the p tag instead of adding more. 要求是在'#b'之后插入insert p标签,并且当再次发生插入操作时,仅替换p标签而不添加更多标签。
Thanks for your help 谢谢你的帮助
Try this: 尝试这个:
function insertP(html)
{
var a = $("#a");
var p = a.find("p")
if(p.length == 0)
{
p = $("<p></p>").appendTo(a);
}
p.html(html)
}
This will insert it directly after #b, within #a, but if it already exists, then it wont insert it again. 这将直接在#a中的#b之后插入它,但是如果它已经存在,则不会再次插入。
$(document).ready(function(){
if ($('#newP').length == 0) {
$('#b').append('<p id="newP">Insert me after #b</p>')
}
});
This function will remove an existing element then add a new element. 此函数将删除现有元素,然后添加新元素。 If one does not exist it will simply add the element.
如果不存在,它将仅添加元素。
<body>
<script type="text/javascript">
$(document).ready(function() {
function addAfterB(pElement) {
if (!$('#b ~ p')) {
$(pElement).insertAfter('#b');
} else if ($('#b ~ p')) {
$('#b ~ p').remove();
$(pElement).insertAfter('#b')
}
}
addAfterB('<p>New Item 1</p>');
});
</script>
<div id="a">
<div id="b"></div>
<p>hello</p>
<div>
You can use $.after()... 您可以使用$ .after()...
<div id="a">
<div id="b"></div>
<div>
...
<script>
$("#b").after("<p>Insert me after #b</p>");
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.