<form name="vegForm" action="veg.aspx" >
<select onchange='this.form.submit()'>
<script type="text/javascript">
for (i = 0; i < veg.length; i++) {
document.write('<option>')
veg[i]
document.write('</option>')
}
</script>
</select>
</form>
你可以想象我很新并且遇到上述问题:/ 任何帮助非常感谢!
答案 0 :(得分:3)
请勿使用document.write()
附加html代码。之后使用document.createElement
和node.appendChild
或(更简单)innerHTML
,如下所示:
<form name="vegForm" action="veg.aspx" >
<select onchange='this.form.submit()' id="mySelect">
</select>
</form>
<script>
(function(){
var out = '';
for (i = 0; i < veg.length; i++) {
out += '<option>' + veg[i] + '</option>';
}
document.querySelector( '#mySelect' ).innerHTML = out;
})();
</script>
答案 1 :(得分:1)
以下是一种方法:http://jsfiddle.net/ur9fr/
JavaScript
var veg = ["1", "2", "3", "4"];
var ddl = document.getElementById("ddlVeg");
for (i = 0; i < veg.length; i++) {
var o = document.createElement("option");
o.text = o.value = veg[i];
ddl.appendChild(o);
}
HTML
<form name="vegForm" action="veg.aspx" >
<select onchange='this.form.submit()' id="ddlVeg">
</select>
</form>
如果您不熟悉JavaScript,那么您会发现像jQuery这样的帮助程序库非常有用。它抽象了一些底层复杂性,并确保跨浏览器的合理兼容性。
jQuery版同样的问题:http://jsfiddle.net/a95Vt/
答案 2 :(得分:0)
将veg[i]
替换为document.write(veg[i])
,您的代码可以正常运行
实施例
<form name="vegForm" action="veg.aspx" >
<select onchange='this.form.submit()'>
<script type="text/javascript">
veg = [1,2,3,4,5] ;
for (i = 0; i < veg.length; i++) {
document.write('<option>')
document.write(veg[i])
document.write('</option>')
}
</script>
</select>
</form>
由于 :)
答案 3 :(得分:0)
你可以这样做:
<form name="vegForm" action="veg.aspx" >
<select onchange='this.form.submit()'>
</select>
</form>
<script>
//array created here - but get it from where ever you need..
var veg = ["leek", "turnip", "carrot"];
(function(){
var form = document.getElementsByName("vegForm")[0];
var select = form.getElementsByTagName("select")[0];
for(var i = 0, len = veg.length; i < len; i++){
var val = veg[i];
selection.options[i] = new Option(val, val);
}
})();
</script>