繁体   English   中英

静态布局与jQuery wrapInner-不同的输出

[英]Static layout vs. jQuery wrapInner - different output

如果我写这样的代码:

<body>
    <xmp>
        <p>hello world</p>
        <div></div>
    </xmp>
</body>

输出将是:

 <p>hello world</p> <div></div> 

但是,代码

<body>
    <p>hello world</p>
    <div></div>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>$( "body" ).wrapInner( "<xmp />" );</script>

不会给我标签。 输出将是:

 hello world 

为什么会发生这种情况以及如何解决?

免责声明:您不应使用<xmp>

它不起作用,因为您使用的是DOM方法,该方法只能移动DOM节点。 身体的内容仍然是要素。 xmp元素仅提供自定义HTML解析算法。 因此,您需要重新分析所有源。 这将破坏元素的所有内部数据。

 var xmp = document.createElement('xmp'); xmp.innerHTML = document.body.innerHTML; // Custom XMP parsing document.body.innerHTML = ''; // Remove current contents document.body.appendChild(xmp); // Insert XMP 
 <p>hello world</p> <div></div> 

但是依靠XMP的魔力是错误的。 解析为文本的正确方法是使用textContent

 var pre = document.createElement('pre'); var code = pre.appendChild(document.createElement('code')); code.textContent = document.body.innerHTML; // Parse as text document.body.innerHTML = ''; // Remove current contents document.body.appendChild(pre); 
 <p>hello world</p> <div></div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM