代码之家  ›  专栏  ›  技术社区  ›  Tony Wierdman

无法在使用脚本放置逗号的textarea中退格

  •  1
  • Tony Wierdman  · 技术社区  · 6 年前

    但由于某种原因,我根本不知道如何使它退格。

       $('#textarea').keyup(function(){
       var str = this.value.replace(/(\w)[\s,]+(\w?)/g, '$1, $2');
       if (str!=this.value) this.value = str; 
       });
    
    <textarea id='textarea'>item1, item2, item3</textarea>
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Irina Potapova    6 年前

    它只启用退格:

    $('#textarea').keyup(function(e) {
      if (e.which === 8) { // backspace detected
          return;
      }
      var str = this.value.replace(/(\w)[\s,]+(\w?)/g, '$1, $2');
      if (str!=this.value) this.value = str; 
    });
    

    $('#textarea').keyup(function(e){
        var str = this.value;
        if (e.which === 8) {
            var tmp = str.split(', ');
            tmp.splice(tmp.length - 1, 1);
            str = tmp.join(', ');
            this.value = str;
            return;
        }
        str = str.replace(/(\w)[\s,]+(\w?)/g, '$1, $2');
        if (str!=this.value) this.value = str; 
    });