在 jQuery 中想要禁用或启用 input 元素可以使用 prop() 方法设置 input 元素的 disabled 属性来完成; 该方法用于设置或返回所选元素的属性和值.
prop() 方法设置或返回被选元素的属性和值. 该方法如果用于返回属性值时, 则返回第一个匹配元素的值; 如果用于设置属性值时, 则为匹配元素集合设置一个或多个属性 / 值对.
语法:
返回属性的值:
$(selector).prop(property)
设置属性和值:
$(selector).prop(property,value)
说明: disabled 属性用于禁用 input 元素.
示例 1: 禁用 input 元素
- <!DOCTYPE html>
- <head>
- <meta charset="UTF-8">
- </head>
- <body style="text-align:center;">
- <h1 style="color:red;">
- 禁用 input 元素
- </h1>
- <input id="input" type="text" name="input" />
- <button onclick="enable_disable()">
- 禁用
- </button>
- <script src="https://code.jquery.com/jquery-1.10.2.js">
- </script>
- <script>
- function enable_disable() {
- $("input").prop('disabled', true);
- }
- </script>
- </body>
- </HTML>
效果图:
示例 2: 启用 input 元素
- <!DOCTYPE HTML>
- <head>
- <meta charset="UTF-8">
- </head>
- <body style="text-align:center;">
- <h1 style="color:red;">
- 启用 input 元素
- </h1>
- <input id="input" type="text" name="input" disabled/>
- <button onclick="enable_disable()">
- 启用
- </button>
- <script src="https://code.jquery.com/jquery-1.10.2.js">
- </script>
- <script>
- function enable_disable() {
- $("input").prop('disabled', false);
- }
- </script>
- </body>
- </HTML>
效果图:
来源: http://www.css88.com/qa/jquery/10494.html