简体   繁体   中英

Why doesn't the JavaScript work for Firefox/Chrome but for IE?

I've written a simple JavaScript to add options to an HTML Select element, the code looks like this:

 function addOption() {
    var newOption = document.createElement('<option value="TOYOTA">');


    var elSel = document.getElementById('mySelect');
    try{
    elSel.add(newOption,null);
    } //Standard
    catch(ex)
    {elSel.add(newOption);
    } //IE Only
    newOption.innerText = "Toyota";
}

I found online tutorial that shows we need to do something like this to get both Firefox/Chrome and IE work. However, currently only IE will work, for FF/Chrome, when I click on the "Add" button, nothing is added to the dropdown, could anybody help? Thanks in advance.

You are supposed to specify the node name, not an HTML string ala jQuery style to createElement afaik.

var el = document.createElement('option')
  , fc = document.createTextNode('blah')
  , s = document.getElementById('foo');

el.value = 'blah';
el.appendChild( fc );
s.appendChild( el )

If you're going to do a lot of UI manipulation, I suggest using a 3rd party library like jQuery to make this easier and more cross-browser compatible.

 $('#mySelect').
      append($("<option value='TOYOTA'>TOYOTA</option>").
      attr("value",'TOYOTA').
      text('TOYOTA')); 

I'm surprised that even works in IE.

Try replacing everything inside the function with this:

var newOption = document.createElement("option");
newOption.setAttribute("value", "TOYOTA");
newOption.appendChild(document.createTextNode("My toyota"));
var elSel = document.getElementById('mySelect');
elSel.appendChild(newOption)

Use this instead:

var mySelect = document.getElementById("mySelect");
mySelect.add(new Option("Toyota", "TOYOTA"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM