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