起初我在我的DOM中有这个:
<li> <span>A</span> </li>
当我这样做:
$( “里”)附加( “<跨度> B< /跨度>” 中);
以下是我查看DOM时得到的内容:
<li> <span>A</span> <span>B</span> </li>
但我想拥有
<li> <span>A</span><span>B</span> </li>
使用javascript innerHTML,问题与jQuery使用append和html函数相同.
谢谢您的帮助
解决方法
您可以通过简单地使用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:只有当ul或ol的直接子项(它不应包含在任何其他元素中)时,li才有效.
此外,您可以使用更复杂的替代方案:
$("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>',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>
参考文献:
> JavaScript:
> document.querySelector()
.
> Element.innerHTML
.
> Element.insertAdjacentHTML()
.
> let
statement.
> Node.nodeType
.
> Node.textContent
.
> jQuery:
> after()
.
> append()
> contents()
> filter()
> last()
> remove()