更新时间:2023-02-07 13:45:35
例如,如果你有一个html文本元素像这样:
For example, if you have a html text element like this:
<p id="textelement">I am a text element</p>
您可以使用JS更改内部文本:
You can change the text inside with JS like this:
<script type="text/javascript">
document.getElementById("textelement").innerHTML = "New text inside the text element!";
</script>
您可以将此技术用于任何可以包含文本的HTML元素,例如选择列表中的选项(< option>
标记)。您可以通过其他方式选择元素:
You can use this technique with any HTML element which can contain text, such as options in a select list (<option>
tag). You can select elements in other ways:
更多信息这里。
PS - 如果要更改元素属性的值,而不是内部文本,则应该使用setAttribute()方法;例如,如果你有:
PS - If you want to change the value of an element's attribute, and not its inner text, you should use the setAttribute() method; for example, if you have:
...
<option id="optionone" value="red">Nice color</option>
...
并想要更改值属性,你应该这样做:
and want to change the value attribute, you should do:
<script type="text/javascript">
document.getElementById("optionone").setAttribute("value", "green");
</script>
有关此内容的更多信息这里。
More about this here.