button 元素的 disabled 属性用法
文章目录
源代码:
<html>
<script>
/*
https://www.w3schools.com/tags/att_button_disabled.asp
The disabled attribute is a boolean attribute.
When present, it specifies that the button should be disabled.
A disabled button is unusable and un-clickable.
The disabled attribute can be set to keep a user from clicking on the button until some other condition has been met (like selecting a checkbox, etc.). Then, a JavaScript could remove the disabled value, and make the button clickable again.
attribute 是跟着 button tag 的。
对于 button DOM object,看这个链接:https://www.w3schools.com/jsref/dom_obj_pushbutton.asp
有一个同名的 property:https://www.w3schools.com/jsref/prop_pushbutton_disabled.asp
*/
function disableMe(){
document.getElementById("myBtn").disabled = true;
}
</script>
<button id="myBtn" type="button" onclick="disableMe()">Click Me!</button>
<button disabled type="button" onclick="alert('clicked')">Click Me 2!</button>
</html>这段 HTML 和 JavaScript 代码示例展示了如何使用 JavaScript 控制 HTML 按钮的可用状态。下面,我将详细介绍每个部分的语法和功能,并解释如何操作这些代码来实现特定的交互效果。
HTML 结构
代码包含了一个 HTML 文档的基本结构,<html> 标签定义了文档的开始和结束。在这个 HTML 文档中,我们主要关注两个部分:内联的 <script> 标签和两个 <button> 标签。
<script> 标签
<script> 标签用于在 HTML 文档中嵌入或引用 JavaScript 代码。在这个例子中,它包含了一个名为 disableMe 的函数,这个函数的作用是禁用 ID 为 myBtn 的按钮。
function disableMe(){
document.getElementById(`myBtn`).disabled = true;
}document.getElementById(myBtn)是一个 DOM(文档对象模型)方法,用于获取 ID 为myBtn的 HTML 元素。.disabled = true;是一个属性赋值操作,它将选中元素的disabled属性设置为true,这使得按钮变为不可点击状态。
<button> 标签
此示例中包含两个按钮。每个按钮都设置了 type="button",这表明这些按钮是普通的按钮,不提交表单数据。
第一个按钮
<button id=`myBtn` type=`button` onclick=`disableMe()`>Click Me!</button>id=myBtn` 为按钮指定一个唯一标识符,使得 JavaScript 能够通过document.getElementById` 方法找到并操作它。onclick=disableMe()是一个事件处理器,当用户点击这个按钮时,它会触发disableMe` 函数,导致按钮自身被禁用。
第二个按钮
<button disabled type=`button` onclick=`alert(`clicked`)`>Click Me 2!</button>disabled属性直接在 HTML 标签中定义,意味着这个按钮在页面加载时就是禁用的,用户无法点击它。onclick=alert(clicked)`` 在用户点击按钮的情况下会触发一个警告框,但因为按钮被禁用,这个事件实际上永远不会被触发。
代码的实用场景
假设在一个网页表单中,你想要确保用户在勾选了某个复选框后才能点击“提交”按钮。这段代码就可以被应用于控制“提交”按钮的启用状态。你可以通过修改 disableMe 函数,使其根据复选框的状态动态地启用或禁用按钮。
结论
通过上述代码和解释,我们可以看到 JavaScript 如何与 HTML 交互,实现动态的用户界面行为。利用 disabled 属性和相关的 DOM 操作,开发者可以创建更加交互性和用户友好的网页应用。这种技术在表单验证、条件触发事件等多种场景中非常有用,是前端开发中常用的一种方法。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论