JavaScript函数在IE 7中无法正常工作。

3

请问如何让这个脚本在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>

2
很少发生“无事发生”。你有收到任何错误信息吗? - Guffa
2个回答

2
首先,在IE-up-to-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接口只是一个外观,经常会出现问题。
处理选项元素的安全方法是每次创建新元素,可以使用document.createElement来编写valuetext属性,也可以像rahul的答案一样使用老式的new Option()构造函数。
最后,您不应该在<select multiple>上使用selectedIndex。因为不一定存在仅有一个选择,所以在任何浏览器中都没有意义。(例如,如果没有选择就单击Add按钮,会出现错误。)相反,循环遍历所有选项并复制每个.selected选项。

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

不带移动的演示

带移动的演示

编辑

这行代码导致了错误。

target.add(copy, null);

add()在Explorer中无法使用标准的第二个参数,即使值为null,因此为了兼容性,可以尝试使用两个参数版本,如果失败,则使用单个参数版本。请参见select.add

谢谢。这个方法有效。你能告诉我我的版本有什么问题吗? - JPro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接