【问题标题】:How to clear an input value on some button press?如何在某些按钮按下时清除输入值?
【发布时间】:2019-01-15 14:30:18
【问题描述】:

我正在尝试在用户按下逗号 (,) 时清除输入。所以我所做的是,在(keypress) 上,我会检查keyCode,如果是逗号,我会通过将输入值设置为input.value = '' 来清除输入。

HTML:

<input type="text" #elem (keypress)="clearInput($event)">

代码:

@ViewChild( 'elem' ) public element;

clearInput( e: KeyboardEvent ) {
 if ( e.keyCode === 44 ) {
    this.element.nativeElement.value = '';
 } else {
   console.log('Not a comma');
 }
}

【问题讨论】:

    标签: javascript html dom-events


    【解决方案1】:

    如果按下逗号,只需return false

    class HomeComponent {
      @ViewChild('elem') public element;
      clearInput(e: KeyboardEvent) {
        if (e.keyCode === 44) {
          this.element.nativeElement.value = '';
          return false;
        } else {
          console.log('Not a comma');
        }
      }
    }
    

    JSFiddle:https://jsfiddle.net/lucakiebel/zrehcwfy/1/

    【讨论】:

      【解决方案2】:

      你需要做 2 个小改动:

      1. 使用keyup事件获取最新键入的键并包含在input的值中
      2. if 条件中使用e.key === ','

      这是工作的JSFIDDLE

      【讨论】:

        【解决方案3】:

        使用Event.preventDefault()

        在您的clearInput 代码中添加preventDefault(),如下所示:

        clearInput (e: KeyboardEvent) {
           if (e.keyCode === 44) {
              e.preventDefault();     // <-- Here
              this.element.nativeElement.value = '';
           } else {
              console.log('Not a comma');
           }
        }
        

        【讨论】:

        • 您可以添加一些解释:逗号的插入将由与您的代码相同的“keyup”事件触发。但是浏览器必须首先运行您的代码,因为您的侦听器不是被动的(它可能会 preventDefault() 或返回 false) - 因此 keypress 事件将首先运行您的侦听器(清除字段),然后是默认侦听器(插入逗号进入空白区域)。所以其他解决方案是 keyUp 或标记你的听众 passive。 - 但是 preventDefault() 对于您的情况来说是最惯用的。
        猜你喜欢
        • 2021-09-25
        • 2017-11-29
        • 2023-04-06
        • 1970-01-01
        • 2019-01-15
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        相关资源
        最近更新 更多