如何在 jQuery 中使用 input 的 readonly 属性?


readonly 是一个 HTML 属性,可以添加到任何 HTML 标签中。当我们将 readonly 属性与任何 HTML 元素一起使用时,它将变成不可编辑的。用户不能文本字段中写入内容,只能读取。

在本教程中,我们将学习使用 jQuery 的各种方法将readonly 属性添加到 HTML 元素。

使用 jQuery 的 attr() 方法

jQuery 的 attr() 方法将属性设置到 HTML 元素。它接受两个参数,我们可以将属性名称作为第一个参数,将属性值作为第二个参数。

语法

用户可以按照以下语法使用 attr() 方法使用 JQuery 将输入设置为只读。

$("#CSS_selector ").attr("readonly", true); 

在上面的语法中,我们将属性名称“readonly”作为 attr() 方法的第一个参数,并将 true 作为第二个参数,表示“readonly”属性的值。

示例

在下面的示例中,我们创建了输入字段以接收用户的文本输入。之后,我们创建了两个按钮,文本分别为“设置为只读”和“设置为可写”。当用户单击按钮时,它将分别调用 addReadonly() 和 removeReadonly() 函数。

在 addReadonly() 函数中,我们使用 attr() 方法添加值为 true 的 readonly 属性。在 removeReadonly() 函数中,我们使用值为 false 的 readonly 属性。

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head> 
<body>
   <h3>Using the <i> attr() method </i> of JQuery to set the readonly attribute to the HTML element</h3>
   <p>Click the respective buttons to add and remove the readonly attribute from the below input.</p>
   <input type = "text" id = "text_inp">
   <br> <br>
   <button onclick = "addReadonly()"> Make Readonly </button>
   <button onclick = "removeReadonly()"> Make Writable </button>
   <script>
      function addReadonly() {
         $("#text_inp").attr("readonly", true);
      }
      function removeReadonly() {
         $("#text_inp").attr("readonly", false);
      }
   </script>
</body>
</html>

使用 jQuery 的 prop() 方法

prop() 方法与 attr() 方法非常相似。attr() 方法用于为 HTML 元素设置属性,而 prop() 方法用于为 HTML 元素添加属性。它也像 attr() 方法一样接受两个参数。

语法

用户可以按照以下语法使用 prop() 方法使用 JQuery 将输入设置为只读。

$("CSS_selector").prop("readonly", true); 

在上面的语法中,CSS_selector 是 HTML 元素的标识符,用于选择元素并使用 prop() 方法添加 readonly 属性。

示例

在下面的示例中,每当用户按下按钮时,它都会调用 makeReadonly() 函数。在 Makereadonly() 函数中,我们使用 prop() 方法将值为 true 的 readonly 属性添加到 input 元素。

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
   <h3>Using the <i> prop() method </i> of JQuery to set the readonly attribute to the HTML element</h3>
   <input type = "text" id = "inp">
   <br> <br>
   <button onclick = "makeReadonly()"> Make Readonly </button>
   <script>
      function makeReadonly() {
         $("#inp").prop("readonly", true);
      }
   </script>
</body> 
</html>

在输出中,用户可以观察到,当他们按下按钮时,文本输入将变为不可编辑。

用户学习了如何在 JQuery 中使用 readonly 属性。用户可以使用 attr() 或 prop() 方法使用 JQuery 将输入设置为只读。此外,用户还可以通过将 false 作为 readonly 属性的值来使用 attr() 和 prop() 方法删除 readonly 属性。

更新于:2023年3月7日

14K+ 浏览量

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.