【问题标题】:Javascript sorting listbox works unless in a table IE8除非在表 IE8 中,否则 Javascript 排序列表框有效
【发布时间】:2010-03-23 14:02:11
【问题描述】:

我有一个功能,当用户选择一个或多个项目时,它将这些项目移动到列表框的顶部(仍处于选中状态)并滚动到顶部以便它们可见。它适用于我测试过的所有主要浏览器。当我让这个函数对表格单元格内的列表框进行排序时,问题就来了。当我这样做并使用 IE8 时,它会正确排序和突出显示,但不会滚动到顶部。 JavaScript 通过基本的 JSLint 检查,网页通过 HTML 验证。我发现 IE8 的怪癖了吗?我是否以错误的方式编写此列表框排序和滚动功能?

<script type="text/javascript">
function Arrange(obj) {
    var countSel = 0, countNSel = 0, i, arr_selected = [], arr_unselected = [];
    for (i = 0; i <= obj.length - 1; i++) {
        if (obj.options[i].selected) {
            //create array with all selected items then sort it
            arr_selected[countSel] = [];
            arr_selected[countSel][0] = obj.options[i].text;
            arr_selected[countSel][1] = obj.options[i].value;
            countSel = countSel + 1;
            arr_selected.sort();
        }
        else {
            //create array with all UNselected items then sort it
            arr_unselected[countNSel] = [];
            arr_unselected[countNSel][0] = obj.options[i].text;
            arr_unselected[countNSel][1] = obj.options[i].value;
            countNSel = countNSel + 1;
            arr_unselected.sort();
        }
    }
    if (countSel !== 0) {
        //overwrite listbox options with selected items
        for (i = 0; i <= countSel - 1; i++) {
            obj.options[i] = new Option(arr_selected[i][0], arr_selected[i][1]);
        }
        //overwrite listbox options with UNselected items
        for (i = 0; i <= countNSel - 1; i++) {
            obj.options[countSel] = new Option(arr_unselected[i][0], arr_unselected[i][1]);
            countSel = countSel + 1;
        }
    }

    //for showing selected items
    //scroll to the top of the list and select the appropriate items
    //it's in reverse order because IE8 wanted to only scroll to the last item selected
    obj.selectedIndex = 0;
    for (i = arr_selected.length - 1; i >= 0; i--) {
        obj.options[i].selected = true;
    }
}
</script>
</head>
<body>
<form name="frm" action="post">
<table><tr><td>test:</td><td>
<select size="4" name="cbostaffcontact" multiple onblur="Arrange(document.forms[0].cbostaffcontact);">
<option value="user1">Al</option>
<option value="user2">Bob</option>
<option value="user3">Christy</option>
<option value="user4">Jane</option>
<option value="user5">Randy</option>
<option value="user6">Tom</option>
<option value="user7">Zed</option>
</select>
</td></tr></table>
</form>

【问题讨论】:

    标签: javascript sorting internet-explorer-8


    【解决方案1】:

    这可能是 IE8 中的一个怪癖,但您的代码实际上并没有说明任何关于滚动的内容,所以我不会责怪 IE8。这是一个简单的指令,应该solve your problem

    obj.scrollTop=0;
    

    【讨论】:

    • 在其他浏览器上,当最后一位代码集在选项上被选中时,它们会向上滚动到列表顶部。我发誓我在某个时候尝试过 scrollTop 没有运气,但它现在可以工作了......无法反驳。谢谢。也感谢 jsfiddle 的链接。这是一个非常有用的网站。
    猜你喜欢
    • 2016-09-11
    • 1970-01-01
    • 2018-06-27
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多