如何使用 JavaScript 动态禁用按钮元素?
在本文中,我们将学习如何使用 javascript 和“disabled”属性动态禁用 HTML 按钮元素。
HTML 按钮元素中的“disabled”属性接受布尔值(true 或 false),根据其值,它将禁用按钮并使其无法使用,即不可点击。我们可以通过将“disabled”属性设置为“true”来禁用 HTML 中的任何按钮。
语法
<button disabled=”true”>Disabled Button</button>
让我们通过一些示例来理解这一点:
示例 1
在这个例子中,我们将通过将“disabled”属性传递为“true”来禁用按钮元素。
文件名:index.html
<html lang="en"> <head> <title>How to disable button element dynamically using JavaScript?</title> </head> <body> <h3>How to disable button element dynamically using JavaScript?</h3> <button id="btn" disabled="true">Disabled button</button> </body> </html>
在这个例子中,我们将使用两个单独的按钮动态禁用和启用 HTML 按钮元素,分别用于启用和禁用按钮。
文件名:index.html
<html lang="en">
<head>
<title>How to disable button element dynamically using JavaScript?</title>
</head>
<body>
<h3>How to disable button element dynamically using JavaScript?</h3>
<button id="btn-p">Enabled button</button>
<div style="display: flex; gap: 10px; margin-top: 10px;">
<button id="enable">Enable</button>
<button id="disable">Disable</button>
</div>
<script>
const btn = document.getElementById("btn-p");
const enableBtn = document.getElementById("enable");
const disableBtn = document.getElementById("disable");
enableBtn.addEventListener("click", () => {
btn.disabled = false;
btn.textContent = "Enabled button";
});
disableBtn.addEventListener("click", () => {
btn.disabled = true;
btn.textContent = "Disabled button";
});
</script>
</body>
</html>
示例 3
在这个例子中,我们将使页面加载后经过一定时间(5 秒)后禁用按钮元素。我们可以使用 setTimeout() 函数将函数的执行延迟指定的时间(以毫秒为单位)。
文件名:index.html
<html lang="en">
<head>
<title>How to disable button element dynamically using JavaScript?</title>
</head>
<body>
<h3>How to disable button element dynamically using JavaScript?</h3>
<button id="btn">Enabled button</button>
<script>
const btn = document.getElementById("btn");
setTimeout(() => {
btn.disabled = true;
btn.textContent = "Disabled button";
}, 5000);
</script>
</body>
</html>
示例 4
在这个例子中,我们将提交表单时禁用按钮元素。我们可以使用 onsubmit 事件在提交表单时执行一个函数,然后在这个函数中禁用按钮。
文件名:index.html
<html lang="en">
<head>
<title>How to disable button element dynamically using JavaScript?</title>
</head>
<body>
<h3>How to disable button element dynamically using JavaScript?</h3>
<form onsubmit="disableButton()">
<input type="text" name="input" placeholder="Enter some text" />
<button type="submit" id="btn">Submit</button>
</form>
<script>
function disableButton() {
const btn = document.getElementById("btn");
btn.disabled = true;
btn.textContent = "Disabled button";
}
</script>
</body>
</html>
结论
在本文中,我们学习了如何使用 javascript 和 disabled 属性动态禁用 HTML 按钮元素。我们可以通过将 disabled 属性设置为 true、动态更改 disabled 属性的值、使用 setTimeout() 函数延迟函数的执行或使用 onsubmit 事件在提交表单时执行函数来禁用按钮。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP