如何在不阻止空格字母输入的情况下 trim 输入值?
例如,如果我编写或粘贴副本“hello world”
,则应将其更正为“hello world”
到目前为止,我的脚本会正确地 trim 粘贴的输入,但如果我手动编写它,它会阻塞空格字母,以便输出为“helloworld”
。
$(function(){
$('.trim').bind('input', function(){
$(this).val(function(_, v){
return v.trim();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="trim" type="text">
最佳答案
尝试在 blur
事件上写入,它将删除当前文本开头和结尾的空格。:
$(function(){
$('.trim').bind('blur', function(){
$(this).val(function(_, v){
return v.trim();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="trim" type="text">
关于javascript - 使用 jquery trim 输入而不阻塞空格输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33606029/