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

时间:2014-02-02 07:19:16

标签: javascript html

我在javascript中使用了innerHTML属性,我突然遇到一个问题,即在<p><h3>....</h3></p>标记中应用.innerHTML时,<p>内的内容未被完全替换。但是当我在<div> <div><h3>....</h3></div>中做同样的事情时,它完全取代了内在的内容。谁能告诉我为什么会这样?

查看此fiddle中发生的情况。

请参阅下面的完整代码:

<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>   

1 个答案:

答案 0 :(得分:1)

它的发生是因为当您在<h3></h3>标记中使用p或任何标题标记时,结束标记超出了范围。

W3C Markup Validator

验证代码时出错

Error on validation


See this Fiddle 。在这个小提琴中你会看到在第二个p中只有<h3></h3>之外和之前的文本将被innerHTML取代。这意味着{ {1}}在<p>之前关闭,因为在 p 中使用 h3 无效

仅解决方案

使用与<h3></h3>类似的CSS样式来标记h3标记内的文字。 Demo Fiddle