且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用于更改文本值的脚本 - Javascript

更新时间: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:


  • getElementById()访问具有指定ID的第一个元素

  • getElementsByName()访问具有指定名称的所有元素

  • getElementsByTagName()访问所有元素具有指定的标记名

  • getElementById() Accesses the first element with the specified id
  • getElementsByName() Accesses all elements with a specified name
  • getElementsByTagName() Accesses all elements with a specified tagname

更多信息这里

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.