【问题标题】:Object someUrl#someHash has no method 'contains'对象 someUrl#someHash 没有方法“包含”
【发布时间】:2013-01-19 17:14:41
【问题描述】:

以下代码在 Chrome 中给我一个错误。 window.location.href 似乎没有返回字符串,但这似乎很疯狂。

代码如下:

var theUrl = "" + window.location.href;
var hashValue = theUrl.contains("#") ? theUrl.split('#')[1] : null; (This is line 6)

这会在 Chrome 中返回以下错误:

Uncaught TypeError: Object someUrl#someHash has no method 'contains' myFile.js:6

(anonymous function) faq.js:6
k jquery.min.js:2
l.fireWith jquery.min.js:2
p.extend.ready jquery.min.js:2
D

有什么想法吗?

编辑:也尝试使用document.URL 无济于事。

【问题讨论】:

  • typeof(window.location.href) 返回什么?
  • 你能做一个可重复的 jsfiddle.net 测试用例吗?
  • @MikkoOhtamaa 现在尝试。
  • @lostsource 返回string全部小写。

标签: javascript google-chrome dom


【解决方案1】:

字符串对象没有名为“contains”的函数,但是您可以使用“indexOf”函数,如果在目标字符串中找到您感兴趣的字符串,则返回值 >= 0,-1否则。

还有一条评论:您可以使用 window.location.hash 获取哈希值,因此您无需执行上述操作,而是需要执行以下操作:

var hashValue = window.location.hash.substr(1) ||空;

【讨论】:

    【解决方案2】:

    .indexOf 也可能有用,而不是 .contains

    hashValue = theUrl.indexOf('#') > -1 ? ... : ...;
    

    【讨论】:

      【解决方案3】:

      目前String.contains 方法似乎仅受 Firefox 19 支持

      String.contains - JavaScript | MDN

      该页面还提到了与 MooTools 的一些不兼容性,可能与您的问题有关。暂时你可以像这样检索哈希值

      var hashValue = window.location.hash.substr(1) || null;
      

      【讨论】:

      • 对于像我在控制台中测试时一样困惑的人来说,stackoverflow 将 .contains() 的 shiv 暴露给 chrome。
      • 你就是男人!我来自 Java 背景,所以我假设所有 Java String 函数都在 Javascript 中。显然不是一个好的假设。
      • @Ben 是的,这令人困惑。模仿 contains 方法的代码正在使用 indexOf ... function (f){ return -1 < this.indexOf(f) }
      猜你喜欢
      • 1970-01-01
      • 2014-10-17
      • 2011-12-08
      • 2015-01-09
      • 2015-02-02
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多