繁体   English   中英

使用innerHTML属性时,p标记(带有嵌套的h3标记)中的内容未完全替换

[英]content not fully replaced in p tag (with nested h3 tag) on using innerHTML property

我在javascript中使用innerHTML属性,突然出现一个问题,当在<p>标记中应用.innerHTML时, <p><h3>....</h3></p>内容没有完全替换。它。 但是,当我在<div><div><h3>....</h3></div>它将完全替换内部内容。 谁能告诉我为什么会这样?

看看这把小提琴正在发生什么。

请参阅下面的完整代码:

<html>
<head>
    <title>innerHTML doubt</title>
    <script type="text/javascript">
        function changeContent(id){
            document.getElementById(id).innerHTML="Content changed in id '"+id+"'.";
        }
    </script>
</head>
<body>
    <p id="p1">
        This content is in first <b>'p'</b> tag (can b fully replaced).
    </p>
    <button onclick="changeContent('p1')">Change upper content</button><hr/>
    <p id="p2">
        <h3>This content is in second 'p' tag with 'h3' tag inside (will not be replaced fully)      </h3>
    </p>
    <button onclick="changeContent('p2')">Change upper content</button><hr/>
    <div id="div1">
        This content is in first 'div' (can b fully replaced).
    </div>
    <button onclick="changeContent('div1')">Change upper content</button><hr/>
    <div id="div2">
        <h3>This content is in second 'div' inside of 'h3'(will also b replaced fully)</h3>
    </div>
    <button onclick="changeContent('div2')">Change upper content</button>
</body>
</html>   

发生这种情况的原因是,当您使用<h3></h3>p标记内的任何标题标记时,结束标记会超出范围。

当我在W3C标记验证器上验证代码时出错

验证错误


请参见此小提琴 。在此小提琴中,您将看到在第二个p<h3></h3>之外和之前的文本将被innerHTML替换。这意味着<p><h3></h3>之前被关闭p中的 h3 无效

唯一的解决方案

使用类似于h3 CSS样式来设置p标签内的文本样式。 演示小提琴

暂无
暂无

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

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