[英]content not fully replaced in p tag (with nested h3 tag) on using innerHTML property
I was using innerHTML property in javascript and suddenly I got a problem that the content inside <p><h3>....</h3></p>
is not being fully replaced when applying .innerHTML
on <p>
tag in it. 我在javascript中使用innerHTML属性,突然出现一个问题,当在<p>
标记中应用.innerHTML
时, <p><h3>....</h3></p>
内容没有完全替换。它。 But when I make the same thing in a <div>
as <div><h3>....</h3></div>
it fully replaces the inner content. 但是,当我在<div>
与<div><h3>....</h3></div>
它将完全替换内部内容。 Can anyone tell me why is it happening? 谁能告诉我为什么会这样?
See what's happening in this fiddle . 看看这把小提琴正在发生什么。
See full code below: 请参阅下面的完整代码:
<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>
Its happening because when you use <h3></h3>
or any heading tag within p
tag ,the closing tag gets out of scope. 发生这种情况的原因是,当您使用<h3></h3>
或p
标记内的任何标题标记时,结束标记会超出范围。
Error when i validate code at W3C Markup Validator 当我在W3C标记验证器上验证代码时出错
See this Fiddle .In this fiddle you will see that in 2nd p
only the text outside and before <h3></h3>
will be replaced by innerHTML.That means <p>
gets closed before <h3></h3>
because using h3 within p is invalid . 请参见此小提琴 。在此小提琴中,您将看到在第二个p
仅<h3></h3>
之外和之前的文本将被innerHTML替换。这意味着<p>
在<h3></h3>
之前被关闭p中的 h3 无效 。
Use CSS style similar to h3
for styling text inside p
tags. 使用类似于h3
CSS样式来设置p
标签内的文本样式。 Demo Fiddle 演示小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.