HTML DOM 按钮的 value 属性
htmlweb developmentfront end technology更新于 2024/6/11 9:48:17
HTML DOM 按钮的 value 属性与 <button> 元素的 value 属性相关联。它指定按钮的隐藏值。value 属性设置或返回按钮 value 属性的值。一些浏览器通常在点击按钮时提交 value 文本,而其他浏览器则提交 <button> 元素之间的文本。
语法
以下是语法 −
设置 value 属性 −
buttonObject.value = text
此处,text 属性值是赋予按钮的初始值。
示例
让我们看一个按钮 value 属性的示例 −
<!DOCTYPE html>
<html>
<body>
<button id="Button1" name="random" value="FirstButton">My Button</button>
<p>Click on the below button to change the above button value</p>
<button onclick="changeFunc()">CHANGE</button>
<p id="Sample"></p>
<script>
function changeFunc() {
document.getElementById("Button1").value = "SecondButton";
var x=document.getElementById("Button1").value;
document.getElementById("Sample").innerHTML="The button value is now "+x;
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击"更改"

我们首先创建了一个按钮,其值为"FirstButton",id 为"button1"。
<button id="Button1" name="random" value="FirstButton>My Button</button>
然后,我们创建了一个按钮 CHANGE,点击后会执行 changeFunc() 函数。
<button onclick="changeFunc()">CHANGE</button>
changeFunc() 方法将使用 id "Button1" 获取第一个按钮元素,并将其值从 "FirstButton" 更改为 "SecondButton"。新更改的按钮值随后被赋值给变量 x,并显示在 id 为 "Sample" 的段落中。
function changeFunc() {
document.getElementById("Button1").value = "SecondButton";
var x=document.getElementById("Button1").value;
document.getElementById("Sample").innerHTML="The button value is now "+x;
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

