jQuery and the this object

jQuery and the this object

本文关键字:object this the and jQuery      更新时间:2023-09-26

jQuery太强大了:(

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

当我尝试添加上述代码时,我得到"this。" Replace不是函数"

我意识到jQuery引用自己为this,那么你打算如何引用this呢?

您发布的代码在String上定义了一个"trim"方法。它允许你这样做:

"  some random string  ".trim();

听起来像是你复制并粘贴了trim函数的BODY到其他jQuery函数中,像这样:

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

试试这个:

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

问题解决:

我忘了在函数末尾加上分号它会进入jQuery函数

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