JavaScript 函数名称与 jQuery 冲突

JavaScript function name conflict with jQuery

本文关键字:jQuery 冲突 函数 JavaScript      更新时间:2023-09-26

我一直在研究一些旧的jsp页面,并试图将jQuery引入其中。但是,当我开始在页面上使用jQuery时,这就是我得到的:

base.js:249 Uncaught TypeError: f is not a function

所以很明显,我们的遗留基础.js和jQuery之间存在冲突。这是导致问题的 base 代码片段.js:

Object.prototype.each = function (f) {
    for (var n = 0; n < this.length; n++)    {
        f (this[n],n);     // This is line 249
    }
    return this;
};

坏消息是我不能轻松地重构这个库,因为还有一些其他的JavaScript库使用它。

我能做些什么吗?谢谢!

快速提示:

这只是一个黑客工作,以解决问题:

Object.prototype.each = function (f) {
  for (var n = 0; n < this.length; n++) {
    if (typeof f == "function")
      f(this[n],n);     // This is line 249
    else
      console.log("You've got a problem here. The f is " + f);
  }
  return this;
};

上面的代码可能会起作用,并帮助您调试内容。