簡體   English   中英

如何使用“value”屬性在只讀和輸入模式之間切換<input>元素

[英]How to alternate between read-only and input mode using the "value" property of <input> element

我正在嘗試制作一個充滿<input>標簽的網頁,您可以在其中在編輯和只讀模式之間切換。 我怎么能輕松做到這一點,我的猜測是使用<input>的 value 屬性?

您可以創建一個狀態變量isEditMode=true並創建一個將狀態值更改為 true 或 false 的按鈕。 現在您可以使用此變量並將其值作為禁用屬性傳遞,如下所示:-

<input disabled={!isEditMode}/> 

因此,如果它不在編輯模式下,那么輸入將被禁用,或者我們可以說在查看模式下。

這是一個小示例,說明如何創建一個類,該類將自動生成輸入並在需要時將它們更新為只讀。 (在小提琴上有一個工作示例) 只需連接一個按鈕即可將輸入更新為

編輯:此解決方案最適合在 vanilla js 中使用

https://jsfiddle.net/0hvjr2uL/25/

class Inp {

    constructor(name, value, placeholder, id, readOnly = false) {
        this.name = name;
        this.value = value;
        this.placeholder = placeholder;
        this.id = id;
        this.readOnly = readOnly;
   }

   render(root){
       let input = document.createElement("input");
       input.name = this.name;
       input.value = this.value
       input.id = this.id;
       input.setAttribute("readonly", this.readOnly); 
    
       root.appendChild(input);
   }

   update() {
       let input = document.getElementById(this.id);
       input.setAttribute("readonly", this.readOnly); 
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM