开发者

jQuery and the this object

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜