jquery split() and indexOf results in “Object doesn't support this property or method”

后端 未结 3 887
生来不讨喜
生来不讨喜 2020-12-10 11:41

I have the following code:

var selected = $(\'#hiddenField\').val().split(\",\");
...
if (selected.indexOf(id) > 0) {
   ... set value ...
}
相关标签:
3条回答
  • 2020-12-10 12:20
    [].indexOf || (Array.prototype.indexOf = function(v,n){
      n = (n==null)?0:n; var m = this.length;
      for(var i = n; i < m; i++)
        if(this[i] == v)
           return i;
      return -1;
    });
    
    0 讨论(0)
  • 2020-12-10 12:23

    There's an jQuery method to overcome the lack of indexOf(), you can use .inArray() instead:

    var selected = $('#hiddenField').val().split(",");
    if ($.inArray(id, selected) > -1) {
       ... set value ...
    }
    

    jQuery.inArray() exists for just this reason...if you're including jQuery already, no need to write the function again. Note: This actually returns a number, like indexOf() would.

    0 讨论(0)
  • 2020-12-10 12:44

    Based on your error message, I'm assuming this is coming from Internet Explorer.

    Surprise! Internet Explorer (including version 8) does not support indexOf for arrays.

    Here is Firefox's implementation you can use:

    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;
      };
    }
    
    0 讨论(0)
提交回复
热议问题