【问题标题】:The mystery of '$.md5 is not a function'“$.md5 不是函数”的奥秘
【发布时间】:2017-08-10 15:48:01
【问题描述】:

我有一个使用 jQuery.MD5 库的 js 代码。它在我的服务器上完美运行:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://example.com/static/js/jquery.md5.js"></script>
</head>
<body>
    <script>
      // my code goes here (declaring variables and functions)
      var code = $.md5('mystring');
      // and a little more code
    </script>
</body>

然后我将它上传到一个网络应用程序(我无法控制),使它看起来像这样并将它放入一个 iframe:

<head>
  <script>
    // some extra variables are declared here
    // double-checked that nothing here can break my code
  </script>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://example.com/static/js/jquery.md5.js"></script>
    <script>
        // some code
        var code = $.md5('mystring');
        // some code
    </script>
</body>

这段代码开始给我$.md5 is not a function 错误。奇怪的事情。试过清缓存,直接把jquery.md5.js代码放到我的,没用。

注意所有代码都可以在我的机器上运行,所以我的JS一定没有问题

更新:有问题的代码行为似乎是不可预测的,这意味着有时它可以正常工作而无需更改。

有什么问题?

【问题讨论】:

  • 好吧,“一些代码”的初始块当然有可能会破坏事情,但我们无法确定这是否属实,因为它不在问题范围内。
  • @Pointy 抱歉,忘记添加了。在那里我声明了函数和变量,没什么特别的。也检查了。不确定将我的完整代码放在这里是否是个好主意,因为它太复杂了
  • 只是为了缩小这里的可能性,如果您在 iframe 之外使用 webapp 的页面结构(正文中带有脚本标签,头部中有额外的变量),它是否会引发相同的错误?
  • 我们能看到 jquery.md5.js 吗?您在上面的示例中使用了 example.com
  • 你总是可以在尝试使用 md5 代码之前添加一个console.log($),以确保它仍然是一个 jQuery 引用。

标签: javascript jquery iframe md5


【解决方案1】:

嗯...这有点尴尬,但问题出在 jQuery 上。我包含在 iframe 中的那个与页面中包含的那个冲突。不知何故,这导致在代码结束后“隐藏”我的 $.md5 函数。

是的,我知道,很明显 jQuery 会导致问题。

【讨论】:

  • 永远不要在同一页面上使用多个版本的 jQuery。您的问题非常普遍,因为人们在同一页面上包含多个版本(甚至同一版本不止一次)。
【解决方案2】:

如果你想使用 jQuery md5 函数,你应该在你的项目中导入 jquery.md5.js 文件。

步骤-

  1. https://github.com/placemarker/jQuery-MD5下载jquery.md5.js文件

  2. 将此文件复制到您的源文件夹中。 (例如:断言/主题/js)

  3. 将该 js 文件导入您的项目。 (例如:&lt;script src="&lt;?= base_url(); ?&gt;/public/assert/theme/js/jquery.md5.js"&gt;&lt;/script&gt;

)

就是这样!你完成了!

【讨论】:

    猜你喜欢
    • 2016-06-28
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多