【问题标题】:How to alternate between read-only and input mode in <input> html tags?如何在 <input> html 标签中切换只读模式和输入模式?
【发布时间】:2021-01-15 23:00:53
【问题描述】:

我正在尝试制作一个充满&lt;input&gt; 标签的网页,人们可以在其中在编辑和只读模式之间切换。我怎么能轻松做到这一点,我的猜测是使用 &lt;input&gt; 的 value 属性?

【问题讨论】:

  • 您是否尝试在输入中添加readonlyreadonly={true}

标签: javascript html reactjs typescript


【解决方案1】:

您可以创建一个状态变量isEditMode=true 并创建一个将状态值更改为真或假的按钮。现在您可以使用此变量并将其值作为禁用属性传递,如下所示:-

<input disabled={!isEditMode}/> 

因此,如果它不在编辑模式下,那么输入将被禁用,或者我们可以说在查看模式下。

【讨论】:

    【解决方案2】:

    这是一个小示例,说明如何创建一个类,该类将自动生成输入并在需要时将其更新为只读。 (在小提琴上有一个工作示例)。只需连接一个按钮即可将输入更新为

    编辑:这个解决方案最适合在 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); 
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多