2010-04-09 38 views
3

任何人都可以请告诉我如何让这个脚本在IE 7中运行?当我运行这个时,没有任何反应。JavaScript函数不能在IE 7中工作

<html> 
    <head> 
    <script language="JavaScript"> 
    function moveSelectedOption() { 
     // Fetch references to the <select> elements. 
     var origin = document.getElementById('origin_select'); 
     var target = document.getElementById('target_select'); 


     // Fetch the selected option and clone it. 
     var option = origin.options[origin.selectedIndex]; 

     var copy = option.cloneNode(true); 

     // Add the clone to the target element. 
     target.add(copy, null); 
    } 
    </script> 
</head> 
<body> 
    <select id="origin_select" multiple> 
     <option value="A">A</option> 
     <option value="B">B</option> 
     <option value="C">C</option> 
    </select> 
    <select id="target_select" multiple> 

     <option value="C1">C1</option> 
    </select> 
    <button onclick="moveSelectedOption()">Add</button> 
<!-- <input type="button" onClick="moveSelectedOption()" value="AddMeToo" /> this does not work either--> 
    </body> 
    </html> 
+0

and ie8 too ..... – Shoban 2010-04-09 11:10:43

+2

“Nothing”很少发生。你有任何错误信息? – Guffa 2010-04-09 11:25:31

回答

0

尝试

var origin = document.getElementById('origin_select'); 
var target = document.getElementById('target_select'); 

// Fetch the selected option and clone it. 
var option = origin.options[origin.selectedIndex]; 
target.options[target.options.length] = new Option(option.text, option.value); 

如果你想删除从原点选择元素的选项,那么你可以使用这个

origin.remove(option); 

Demo without move

Demo with move

编辑

此行是导致错误。

target.add(copy, null); 

的add()不会为了 兼容一个可以尝试的 两个参数的版本,并在出现故障时,在浏览器的标准 第二个参数的工作,即使 null值,所以, 使用单参数版本。

select.add

+0

谢谢。这工作。你能告诉我我的版本有什么问题吗? – JPro 2010-04-09 11:24:30

+0

看到我编辑的答案。 – rahul 2010-04-09 11:34:10

+0

@JPro接受这个答案,如果它的工作 – ant 2010-04-09 12:04:10

2

首先,你不能使用IE浏览器,先进的7 add(option, null)由于错误(你会得到“类型不匹配”)。你将不得不使用add(option),但当然这是非标准的,并在其他地方打破。为了安全起见,请使用select.add(option, options.length)select.options[options.length]= option

接下来,当该选项已经在IE-up-to-7中选择时(即使在克隆后!),由于另一个错误(你会得到“无效参数” )。 IE对<option>元素的处理方式很多,其来源是IE的选择框是本地Windows小部件,而不是浏览器实现的对象。因此,IE的HTMLOptionElement接口只是一个façade,经常会滑倒。

的安全的方式来处理选项元素是重新建立他们每一次,或者使用document.createElement和写入valuetext性能,或使用旧学校new Option()构造函数中拉胡尔的回答。

最后,您不应该在<select multiple>上使用selectedIndex。由于不一定只有一种选择,因此在任何浏览器中都没有意义。 (例如,单击没有选择的Add按钮会出现错误。)而是循环所有选项并复制每个选项.selected

+0

感谢您的解释。 – JPro 2010-04-09 11:46:11