2009-05-29 47 views
0

我有以下几点:我如何获得eval在IE中正常运行?

<select id="price_select"></select> 

我有一个事件处理程序调用以下:

var selected_option = "one"; 
var option_one = "<option>Option Contents</option>"; 
document.getElementById('price_select').innerHTML = eval('option_' + selected_option); 

作品只是在Firefox罚款,但不是在IE6。

+0

即使我对你做任何你想做的没有问题,知道这一点:使用eval()是所有人通常都皱起眉头,特别是在这种情况下,有其他方法可以完成你正在尝试做的事情...... – 2009-05-29 04:09:23

回答

4

难道你不能这样做吗?

var selected_option = "one"; 
var options = { "one": "<option>Option Contents</option>" }; 
document.getElementById('price_select').innerHTML = options[selected_option]; 
+0

为什么?这是一个散列,就像一个关联数组key =>值。 我访问的选项元素与键= selected_option,这将是“”(其中,btw,是一个字符串,没有.text属性):) – MartinodF 2009-05-29 02:35:33

0

的innerHTML并不在IE6的下拉列表中,因为它是一个错误的工作。

的eval()确实在IE 6

0

尝试这项工作:

eval("var x= " + ('option_' + selected_option)); 
document.getElementById('price_select').innerHTML = x; 
2

工作过的是什么marknt15MartinodF说,你应该能够使用本地DOM操作做你在做什么试图没有使用eval()

var selected_option = "one"; 
var options = { "one": {"value": "0", "text":"OptionContents"} }; 
var e = document.createElement("option"); 

if(e.innerText) {// IE sets innerText like this 
    e.innerText = options[selected_option].text; 
} else { // W3C sets inner text like this 
    e.childNodes[0].nodeValue = options[selected_option].text; 
} 

e.value = options[selected_option].value; 

document.getElementById('price_select').appendChild(e); 

你可能要考虑使用一个全功能的JavaScript框架,如jQuery或原型做出这样的事情更容易,虽然处理。

相关问题