javascript函数在IE 7中不起作用

javascript函数在IE 7中不起作用,javascript,html,Javascript,Html,谁能告诉我如何让这个脚本在IE7中运行?当我运行这个时,什么都没有发生 <html> <head> <script language="JavaScript"> function moveSelectedOption() { // Fetch references to the <select> elements. var origin = document.getElementByI

谁能告诉我如何让这个脚本在IE7中运行?当我运行这个时,什么都没有发生

    <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>

函数moveSelectedOption(){
//获取对元素的引用。
var origin=document.getElementById('origin_select');
var target=document.getElementById('target_select');
//获取所选选项并克隆它。
var option=origin.options[origin.selectedIndex];
var copy=option.cloneNode(true);
//将克隆添加到目标元素。
target.add(复制,空);
}
A.
B
C
C1
添加
试试看

如果要从“原点选择”元素中删除该选项,则可以使用此选项

origin.remove(option);

编辑

这一行导致了错误

target.add(copy, null);
add()不适用于标准 资源管理器中的第二个参数,即使是 值为null,因此为了 兼容的人可以试试 两个参数版本,失败时, 使用单参数版本


请参见

首先,由于存在错误,您无法在IE-up-to-7中使用
添加(选项,null)
(您会得到“类型不匹配”)。您必须使用
add(option)
,但这当然是非标准的,并且在其他地方会中断。为了安全起见,请使用
select.add(option,options.length)
,或
select.options[options.length]=option

接下来,由于另一个bug(您会得到“无效参数”),当选项已经在IE-up-7中的select中时(即使在克隆之后!),您不能将该选项添加到select中。IE对
元素的处理在很多方面都是无效的,其根源在于IE的选择框是本机Windows小部件,而不是由浏览器实现的对象。因此,IE的HTMLOptionElement接口只是一个表面,经常会出错

处理选项元素的安全方法是每次都重新创建它们,或者使用
document.createElement
并编写
值和
文本
属性,或者使用rahul回答中的老式
new option()
构造函数


最后,您不应该在
上使用
selectedIndex
。因为不一定只有一个选择,所以在任何浏览器中都没有意义。(例如,在没有选择的情况下单击
添加
按钮会出现错误。)相反,请循环所有选项并复制每个
。选中的

谢谢。这起作用了。你能告诉我我的版本有什么问题吗?“什么都没有”很少发生。您是否收到任何错误消息?
target.add(copy, null);