添加/删除选项仅在Firefox中失败

时间:2011-03-10 21:05:59

标签: javascript html css select

我有一个简单的网页添加&从动态选择元素中删除选项。该代码适用于Chrome& IE,但它在Firefox中失败(当我点击添加没有任何事情发生&删除按钮甚至没有显示?)

您认为我做错了什么?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/homepage.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title></title>
    <script LANGUAGE="JavaScript" type = "text/javascript">
    <!--

        function addOption()
        {
            var listbox = document.getElementById( "listbox" );
            var lastIndex = listbox.options.length-1;
            var newOption = document.createElement( "option" );
            newOption.text = "New";
            newOption.value = "New";

            try
            {
                listbox.add( newOption, lastIndex );  // standards compliant; doesn't work in IE  
            }
            catch (ex) 
            { 
                listbox.add( newOption, listbox.selectedIndex ); // IE only 
                alert( "In addOption(): " + ex ); 
            } 

        }

        function deleteOption()
        {
            //alert( "1" );
            var listbox   = document.getElementById( "listbox" );
            var lastIndex = listbox.options.length-1;

            if ( lastIndex < 0 )
                return;

            listbox.remove( lastIndex );
            //alert( "2" );
        }
    -->
    </script>

    <style type="text/css" media="all">
        <!--

            div { text-align: center; }
            button { width: 100px; height: 20px; }
            #listbox { width: 200px; height: 200px;

        -->
    </style>
</head>

<body>

    <div>
        <select id="listbox" multiple="multiple">
            <option>Test</option>
        </select>

        <button value="Add"    onclick="addOption()"/>
        <button value="Delete" onclick="deleteOption()"/>
    </div>

</body>
<!-- InstanceEnd -->
</html>

2 个答案:

答案 0 :(得分:3)

使用:

<button value="Add"    onclick="addOption()">Add</button>
<button value="Delete" onclick="deleteOption()">Delete</button>

而不是

<button value="Add"    onclick="addOption()"/>
<button value="Delete" onclick="deleteOption()"/>

button元素需要结束标记:http://www.w3.org/TR/html401/interact/forms.html#h-17.5

另外,使用

listbox.options.add( newOption, lastIndex );

而不是

listbox.add( newOption, lastIndex );

见这里:http://jsfiddle.net/wEFHA/4/

答案 1 :(得分:2)

document.createElement('<option>')正在IE中工作但不在FF中工作 document.createElement('option')正在IE和FF中工作。