【问题标题】:Why is indexOf not working in Internet Explorer?为什么 indexOf 在 Internet Explorer 中不起作用?
【发布时间】:2010-09-13 02:26:40
【问题描述】:

此函数在表单提交期间执行,在 Firefox 和 Chrome 中运行良好,但在 IE 中不行。我怀疑它是 indexOf,但我似乎找不到让它工作的方法。

function checkSuburbMatch(e) {

var theSuburb = document.getElementById('suburb').value;
var thePostcode = document.getElementById('postcode').value;

var arrayNeedle = theSuburb + " (" + thePostcode + ")";

if(suburbs.indexOf(arrayNeedle) != -1) {
    alert("Suburb and Postcode match!");
    return false;
} else {
    alert("Suburb and Postcode do not match!");
    return false;
}

}

【问题讨论】:

标签: javascript internet-explorer indexof


【解决方案1】:

IE在Array上根本没有这个方法,不过你可以自己加,from MDC

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

这会添加.indexOf(),如果它丢失了(此时这意味着你在 IE

【讨论】:

  • 这似乎不起作用,并且使它在 Firefox 中也停止工作。这个需要放在函数调用之后还是脚本开始处?
  • @David:需要在调用前声明。
【解决方案2】:

如果您已经在项目中使用 jQuery,则可以使用 $.inArray()

http://api.jquery.com/jQuery.inArray/

【讨论】:

    【解决方案3】:

    indexOf() 在 MSIE 11 和其他它不喜欢非字符串变量。在郊区添加 .toString() 它应该可以修复它。

    【讨论】:

      【解决方案4】:

      这个函数在使用关联数组时很糟糕。

      如果您将该函数放入代码中并执行此操作

      var a = new Array();
      
      a["one"] = "1";
      
      for(var i in a){
      
         alert(i)
      
      }
      

      你得到 0, indexOf 这意味着你插入了 indexOf 作为你创建的每个数组的键

      但数组应该只有一个键,即“一”

      使用 jQuery!

      -梅基亚斯

      【讨论】:

        猜你喜欢
        • 2011-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多