[英]In HTML/JavaScript, how do you dynamically set a header/paragraph element's text without overwriting anything else?
When you search for how to set a paragraph or header element's text dynamically, you keep coming across pretty much the same line of code: 当您搜索如何动态设置段落或标题元素的文本时,您会遇到几乎相同的代码行:
document.getElementById("header").innerHTML = "some text";
This isn't entirely correct though. 但这并不完全正确。 Take the following example:
请看以下示例:
<html>
<head />
<body>
<h1 id="header" />
<p id="p1" />
<script type="text/javascript">
document.getElementById("header").innerHTML = "header";
document.getElementById("p1").innerHTML = "p1";
</script>
</body>
</html>
The first JavaScript line pretty much deletes p1
from the page, even though p1
and header
have nothing to do with each other in the raw HTML. 第一个JavaScript行几乎从页面中删除了
p1
,即使p1
和header
在原始HTML中没有任何关系。 When wrapping the second JavaScript line in a try...catch block, the error that's caught is: 在try ... catch块中包装第二个JavaScript行时,捕获的错误是:
document.getElementById(...) is null
The same problem exists when you use textContent
instead of innerHTML
. 使用
textContent
而不是innerHTML
时存在同样的问题。 I'm a little surprised that everybody is saying that this is how you're supposed to change the text of an element when it really doesn't suit that purpose very well. 我有点惊讶的是,每个人都说这是你应该如何更改元素的文本,当它真的不适合这个目的时。 What's the right way to set this up?
设置它的正确方法是什么?
p
and h1
are not "empty elements", meaning they're not closed in the same tag that opens them (like img
and br
). p
和h1
不是“空元素”,这意味着它们不会在打开它们的同一个标签中关闭(如img
和br
)。 If you write them like that, they're not valid tags and the browser will ignore them (which is why document.getElementById
can't find them). 如果你这样写它们,它们就不是有效的标签,浏览器会忽略它们(这就是为什么
document.getElementById
找不到它们)。 Try this instead: 试试这个:
<html>
<head></head>
<body>
<h1 id="header"></h1>
<p id="p1"></p>
<script type="text/javascript">
document.getElementById("header").innerHTML = "header";
document.getElementById("p1").innerHTML = "p1";
</script>
</body>
</html>
Change your html to this : 将您的HTML更改为:
<h1 id="header"></h1>
<p id="p1"> </p>
And try your JavaScript code now they will work, because they are not empty elements. 现在尝试使用JavaScript代码,因为它们不是空元素。
I think the main issue you are having is with the way you are setting up the closing tags like so: <h1 id="header"/>
with / instead of a closing statement. 我认为你遇到的主要问题是设置结束标签的方式如下:
<h1 id="header"/>
with /而不是结束语句。 This is incorrect and you need to close it like so: <h1 id="header"></h1>
The same is true for the <p>
tag and many others. 这是不正确的,你需要像这样关闭它:
<h1 id="header"></h1>
<p>
标签和许多其他标签也是如此。 There are some exceptions to this rule which you can find here: 您可以在此处找到此规则的一些例外情况:
http://www.w3schools.com/html/html_elements.asp http://www.w3schools.com/html/html_elements.asp
Here is an example fiddle with the actual result! 这是一个实际结果的例子!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.