[英]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: 我编写了一个简单的JavaScript来为HTML Select元素添加选项,代码如下所示:
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. 我发现在线教程显示我们需要做这样的事情来使Firefox / Chrome和IE工作。 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? 但是,目前只有IE可以使用,对于FF / Chrome,当我点击“添加”按钮时,没有任何内容添加到下拉列表中,有人可以帮忙吗? Thanks in advance. 提前致谢。
You are supposed to specify the node name, not an HTML string ala jQuery style to createElement
afaik. 您应该指定节点名称,而不是HTML字符串ala jQuery样式到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. 如果你要进行大量的UI操作,我建议使用像jQuery这样的第三方库来使这更容易,更兼容跨浏览器。
$('#mySelect').
append($("<option value='TOYOTA'>TOYOTA</option>").
attr("value",'TOYOTA').
text('TOYOTA'));
I'm surprised that even works in IE. 我很惊讶甚至可以在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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.