如何在 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+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告