Frage

Why does this code work in IE, but not in Firefox?

elems = document.forms[0].getElementsByTagName("select");
for (i = 0; i < elems.length; i++) {
   if (elems[i].studentid && elems[i].studentid == studid && elems[i].selectedIndex == 0)
      elems[i].selectedIndex = 1;
}
War es hilfreich?

Lösung

It would help greatly to see a relevant snippet of HTML.

In the code, it seems that elems[i] is a select element, and elems[i].studentid is an attempt to read a property named studentid. The related HTML might be like:

<select studentid="..." ...>

There is no standard HTML select element attribute called studentid, therefore even if that attribute has been added to the select element, it will not be available as a property in Firefox (and probably other browsers). Therefore the test fails at:

elems[i].studentid

where Firefox will return undefined, which evaluates to false. However, IE does add non–standard attributes as properties, so the test may pass in IE if the attribute has been set.

To access non–standard attributes the getAttribute method should be used for cross–browser compatibility, so the test might be:

elems[i].hasAttribute('studentid') && elems[i].getAttribute('studentid') == studid ... 

There doesn't seem to be any value in the hasAttribute test, so that can probably be dropped. Since elems[i] is used multiple times, I'd also store the result:

var elem = elems[i];
if (elem.getAttribute('studentid') == studid && elem.selectedIndex == 0) {
  elem.selectedIndex = 1;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top