jQuery 用 «-» 替换空格 不适用于 <input type="email" />

jQuery Replace whitespace by «-» Not working with <input type="email" />

我无法用 «-» 替换空格。为什么?

但是 ein type="text" 有效

我的代码HTML很简单:

<input type="text" class="demo" placeholder="type=text" /><br /><br />
<input type="email" class="demo" placeholder="type=email" />

我的代码jQuery:

$(document).on("keyup",".demo",function(e) {
            
        
    $(this).val($(this).val().replace(/\s+$/g, "-"));

});

我的 jsFiddle:

https://jsfiddle.net/6qo973vm/11/

解决方案?

因为对于输入类型的电子邮件,返回的值文本总是被修剪,您可以用所需的字符替换最后的 space。

已更新 fiddle here

片段:

$(document).on("keyup", ".demo", function (e) {
    if (e.keyCode == 32) {  // in case of space...
        if (this.value.indexOf(' ') != -1) { // if the space is inside string
            this.value = this.value.replace(/\s+/g, "-");
        } else {  // for type = email: the space is at the end: add a final char.....
            this.value = this.value + '-';
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<h1>Replace whitespace by «-» Not workin in input type email</h1>
<input type="text" class="demo" placeholder="type=text"/><br/><br/>
<input type="email" class="demo" placeholder="type=email"/>

我还没有真正研究为什么这样的输入框会这样。在调试时,我还注意到 event.target.value 在调用 .val() 之前已经被修剪了。但是,查看以下代码片段也许您会发现一些我尚未发现的内容。还有一个可能需要修复的延迟。

$(document).on("keyup", ".demo", function(e) {
  if (this.id === "email") {
    document.getElementById("email").value = document.getElementById("email").value.replace(" ", "-")
  } else {
    $(this).val($(this).val().replace(/\s+$/g, "-"));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Replace whitespace by «-» Not workin in input type email</h1>
<input type="text" class="demo" placeholder="type=text" /><br /><br />
<input type="email" id="email" class="demo" placeholder="type=email" />