2010-09-13 10 views
5

Esta función se ejecuta durante los formularios en Enviar y funciona bien en Firefox y Chrome, pero no en IE. Sospecho que es indexOf, pero parece que no puedo encontrar la manera de hacerlo funcionar.¿Por qué el índiceOf no funciona en Internet Explorer?

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; 
} 

} 
+0

¿Qué contiene "suburbios" variables? – Tim

+0

Es un conjunto de cadenas que van en la línea de "suburbName (postCode)" – David

+0

posible duplicado de [¿Por qué no funciona IndexOf en una matriz IE8?] (Http://stackoverflow.com/questions/3629183/why-doesnt -indexof-work-on-an-array-ie8). Ver también: [Cómo arreglar Array indexOf() en JavaScript para navegadores IE] (http://stackoverflow.com/questions/1744310/), [Array indexOf implementation for Internet Explorer] (http://stackoverflow.com/questions/2868696) – CMS

Respuesta

17

IE simplemente no tiene este método en Array, se puede añadir por sí mismo, sin embargo, 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; 
    }; 
} 

Esto añade .indexOf() si no se encuentra (en este punto que significa que está en IE < 9) luego puede usarlo. ¿En cuanto a por qué incluso IE8 ya no tiene esto? No te puedo ayudar ...

+0

Esto no pareció funcionar, y también dejó de funcionar en Firefox. ¿Es necesario colocar esto después de que se llama a la función o al comienzo del script? – David

+0

@David: debe declararse antes de que se llame. –

-1

esta función es malo cuando se utilizan matrices asociativas.

si pones esa función en el código y hacerlo

var a = new Array(); 

a["one"] = "1"; 

for(var i in a){ 

    alert(i) 

} 

Se obtiene 0, indexOf lo que significa que ha insertado indexOf como una clave a cada serie se crea

pero la matriz sólo debe tener una tecla y esa es "una"

use jQuery!

-Mekias

0

indexOf() en MSIE 11 y otros que no le gustan las variables que no son cadenas. En los suburbios, agregue .toString() y debería arreglarlo.

Cuestiones relacionadas