首页 文章

不能在textarea中退格,它使用脚本来放置逗号

提问于
浏览
1

我正在使用此脚本在您键入的每个项目后自动放置逗号空格并按空格键 .

但由于某种原因,我根本无法弄清楚如何让它退格 .

我希望它能够删除每个退格的整个项目和尾随逗号 .

$('#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 回答

  • 0

    它只是启用退格:

    $('#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; 
    });
    

相关问题