开发者

jQuery and the this object

开发者 https://www.devze.com 2023-04-09 07:39 出处:网络
jQuery is too overp开发者_高级运维owering :( String.prototype.trim = function () { return this.replace(/^(\\s| |\\u00A0)+|(\\s| |\\u00A0)+$/g, \"\");

jQuery is too overp开发者_高级运维owering :(

String.prototype.trim = function () {
    return this.replace(/^(\s| |\u00A0)+|(\s| |\u00A0)+$/g, "");
}

when I try to add the above code, I get "this.replace is not a function".

I realise that jQuery references itself as this, so how are you meant to reference this?


The code you've posted defines a "trim" method on a String. That allows you to do this:

"  some random string  ".trim();

Sounds like you've copied and pasted the BODY of that trim function into some other jQuery function, like this:

$('#myfield').change(function () {
  this = this.replace(/^(\s| |\u00A0)+|(\s| |\u00A0)+$/g, "");
});

Try this instead:

$('#myfield').change(function () {
  $(this).val($(this).val().trim());
});


Problem solved:

I forgot to put the semi colon on the end of the function and it was running in to the jQuery function

String.prototype.trim = function () {
    return this.replace(/^(\s| |\u00A0)+|(\s| |\u00A0)+$/g, "");
};

(function ($) {
......
0

精彩评论

暂无评论...
验证码 换一张
取 消