【问题标题】:How do you make the input value blank when you click the button? [duplicate]单击按钮时如何使输入值变为空白? [复制]
【发布时间】:2018-09-06 10:10:38
【问题描述】:

我正在创建一个cmets部分,但是有一个问题:点击post时如何将输入值设为空白?

<input type="text" value="" id="stuffed" />
<button onclick="post()">Post</button>

<script>
  function post(){
    var x = document.getElementById("stuffed").value;
    document.getElementById("paragraph").innerHTML = "&lt;me&gt; " + x;
  }
</script>
<p style="color: #ffffff;" id="paragraph"></p>

这样会发布评论(稍后我将使用 css 来装饰它),但在它说“评论”的地方仍然有之前发布的评论。你如何将它的值返回为空白?

【问题讨论】:

  • 重置表格,不是吗?或document.getElementById("stuffed").value="" ?
  • @whoever 编辑了我的代码 感谢您的帮助,但它不是 xHTML。不过还是谢谢

标签: javascript css html


【解决方案1】:

好吧,只分配一个空值:

document.getElementById("stuffed").value = ''

function post() {
  var x = document.getElementById("stuffed").value;
  document.getElementById("paragraph").innerHTML += "<br>&lt;me&gt; " + x;
  
  document.getElementById("stuffed").value = ''
}
<input type="text" aria-label="Comments" placeholder="Comments" value="" style="padding:10px 50px 10px 5px" id="stuffed"></input><button onclick="post()" style="text-decoration: none; color: #ffffff; background-color: #5dbbd4; padding: 12px 10px 12px 10px; border-width: 0px;">Post</button>


<p style="color: #000;" id="paragraph"></p>

采用addEventListener函数将事件绑定到元素。

document.getElementById('postbtn').addEventListener('click', post);

function post() {
  var input = document.getElementById("stuffed");
  var x = input.value;
  document.getElementById("paragraph").innerHTML += "<br>&lt;me&gt; " + x;

  input.value = '';
  input.focus();
}
<input type="text" aria-label="Comments" placeholder="Comments" value="" style="padding:10px 50px 10px 5px" id="stuffed"></input><button id="postbtn" style="text-decoration: none; color: #ffffff; background-color: #5dbbd4; padding: 12px 10px 12px 10px; border-width: 0px;">Post</button>


<p style="color: #000;" id="paragraph"></p>

【讨论】:

    【解决方案2】:

    只需添加这一行:

    document.getElementById("stuffed").value = "";
    

    这里是您的代码的 sn-p:

    function post(){
      var x=document.getElementById("stuffed").value;
      document.getElementById("paragraph").innerHTML="&lt;me&gt; " + x;
      document.getElementById("stuffed").value = "";
    }
    <input type="text" aria-label="Comments" placeholder="Comments" value="" style="padding:10px 50px 10px 5px" id="stuffed"></input><button onclick="post()" style="text-decoration: none; color: #ffffff; background-color: #5dbbd4; padding: 12px 10px 12px 10px; border-width: 0px;">Post</button>
    
    <p style="color: #ffffff;" id="paragraph"></p>

    【讨论】:

      【解决方案3】:

      您必须将其值设置回您想要的值。在你的情况下,它不是这样:

      document.getElementById("mytext").value = "我的价值";

      确保在完成数据后执行此操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-15
        • 2022-09-27
        • 2020-03-02
        • 1970-01-01
        • 2018-01-13
        • 1970-01-01
        • 2020-03-19
        • 1970-01-01
        相关资源
        最近更新 更多