更改文本值的脚本 - Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6243441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:54:45  来源:igfitidea点击:

Script to change value of a text - Javascript

javascript

提问by Sourav

From this question i came to know text element's value can be changed by JS Set maximum number of item in Select List - html

从这个问题我开始知道文本元素的值可以通过 JS Set maximum number of item in Select List - html 来改变

can anyone give some code or some tips ?

任何人都可以提供一些代码或一些提示吗?

My intention is not hacking, i need to know this, coz i'm writing a web app where most of the validation is done by JS

我的意图不是黑客攻击,我需要知道这一点,因为我正在编写一个 Web 应用程序,其中大部分验证都是由 JS 完成的

Edit
Looking for guide on running JS from client side on a page served by a server [on some text where it's readonly="true"] !

Edit
寻找有关在服务器提供的页面上从客户端运行 JS 的指南 [在某些文本上,它是readonly="true"]!

回答by faken

For example, if you have a html text element like this:

例如,如果您有这样的 html 文本元素:

<p id="textelement">I am a text element</p>

You can change the text inside with JS like this:

您可以像这样使用 JS 更改里面的文本:

<script type="text/javascript">
    document.getElementById("textelement").innerHTML = "New text inside the text element!";
</script>

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:

您可以将此技术用于任何可以包含文本的 HTML 元素,例如选择列表(<option>标记)中的选项。您可以通过其他方式选择元素:

  • 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
  • getElementById()访问具有指定 id 的第一个元素
  • getElementsByName()访问具有指定名称的所有元素
  • getElementsByTagName()访问具有指定标记名的所有元素

More info here.

更多信息在这里

PS - If you want to change the valueof an element's attribute, and not its inner text, you should use the setAttribute() method; for example, if you have:

PS - 如果你想改变一个元素的属性,而不是它的内部文本,你应该使用 setAttribute() 方法;例如,如果您有:

...
<option id="optionone" value="red">Nice color</option>
...

and want to change the valueattribute, you should do:

并想要更改value属性,您应该执行以下操作:

<script type="text/javascript">
    document.getElementById("optionone").setAttribute("value", "green");
</script>

More about this here.

更多关于这里