您可以通过简单地使用代替来解决或至少避免该问题:after()
append()
$("li span").last().after("<span>C</span>");
$("li span").last().after("<span>C</span>");
$('#generatedHTML').text($('li').html());
#generatedHTML {
white-space: pre-wrap;
font-family: mono;
padding: 0.5em;
margin: 0;
background-color: #eee;
}
#generatedHTML::before {
content: "Created HTML: ";
color: #999;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<span>A</span>
</li>
</ul>
<div id="generatedHTML"></div>
另外,请注意我更正了您的 HTML:anli
仅在a ul
or的直接子级时有效ol
(它不应包含在任何其他元素中)。
此外,您可以使用更复杂的替代方案:
$("li").append("<span>B</span>").contents().filter(function(){
return this.nodeType === 3;
}).remove();
$("li").append("<span>B</span>").contents().filter(function(){
return this.nodeType === 3;
}).remove();
$('#generatedHTML').text($('li').html());
#generatedHTML {
white-space: pre-wrap;
font-family: mono;
padding: 0.5em;
margin: 0;
background-color: #eee;
}
#generatedHTML::before {
content: "Created HTML: ";
color: #999;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<span>A</span>
</li>
</ul>
<div id="generatedHTML"></div>
虽然已经有一段时间了,但我认为还值得添加上面的纯 JavaScript 版本:
let htmlToAppend = '<span>B</span>',
span = document.querySelector('li span');
span.insertAdjacentHTML(
'afterend', htmlToAppend
);
document.querySelector('#generatedHTML').textContent = span.parentNode.innerHTML;
let htmlToAppend = '<span>B</span>',
span = document.querySelector('li span');
span.insertAdjacentHTML(
'afterend', htmlToAppend
);
document.querySelector('#generatedHTML').textContent = span.parentNode.innerHTML;
#generatedHTML {
white-space: pre-wrap;
font-family: mono;
padding: 0.5em;
margin: 0;
background-color: #eee;
}
#generatedHTML::before {
content: "Created HTML: ";
color: #999;
display: block;
}
<ul>
<li>
<span>A</span>
</li>
</ul>
<div id="generatedHTML"></div>
参考: