jQuery 修剪() 文本输入字段的值属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6613706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:07:39  来源:igfitidea点击:

jQuery to trim() a text input field's value attribute?

jqueryvalidation

提问by Scott B

In this jQuery, I'm able to bind the paste event to validate the form field, but my method inside the function is apparently wrong. I'm not getting an alert at all.

在这个 jQuery 中,我能够绑定 paste 事件来验证表单字段,但是我在函数中的方法显然是错误的。我根本没有收到警报。

I just want to trim the text that's input and return that as the value of the form input text field #adsense_client_id.

我只想修剪输入的文本并将其作为表单输入文本字段的值返回#adsense_client_id

$("#adsense_client_id").bind('paste', function(e) {
    $(this).attr('value') = $.trim(this).val();
    alert($(this).val()); //why no alert?
});

回答by MacMac

The $.trimis a function which needs a variable/string inside it, since you did not wrap $(this).val()with $.trimin order for it to work.

$.trim是一个需要在其中包含变量/字符串的函数,因为您没有对其进行换行$(this).val()$.trim使其工作。

As you need a timeout for the paste to be caught, do it like this:

由于您需要超时才能捕获粘贴,请执行以下操作:

$("#adsense_client_id").bind('paste', function(e) {
    var clientId = $(this);
    setTimeout(function(){
        clientId.val($.trim(clientId.val()));
        alert(clientId.val());
    });
});

Demo.

演示

回答by Christian Smorra

check out this response Catch paste input

查看此响应 捕获粘贴输入

apparently you need to set a small settimeout to catch the pasted input value

显然你需要设置一个小的 settimeout 来捕捉粘贴的输入值

this should do the trick:

这应该可以解决问题:

("#adsense_client_id").bind('paste', function(e) {
    $(this).attr('value') = $.trim($(this).val());
    var el = $(this);
    setTimeout(function()
    {
        var text = $(el).val();
        alert($.trim(text)); //why no alert?
    }, 500);
});

回答by jcarrenog

I know this is a very old question but this is pretty obvious...

我知道这是一个非常古老的问题,但这很明显......

The only poblem with your code is with this line:

您的代码唯一的问题是这一行:

$(this).attr('value') = $.trim(this).val();

Which is incorrect in JavaScript. I think you meant this:

这在 JavaScript 中是不正确的。我想你的意思是:

$(this).attr('value', $.trim(this).val());

And the resulting code works perfectly:

结果代码完美运行:

$("#adsense_client_id").bind('paste', function(e) {
    $(this).attr('value', $.trim(this).val());
    alert($(this).val()); 
});

回答by Espiral

$(this).val($(this).val().trim());
alert($(this).val());