我需要提供一个按钮,允许用户选择多个列表框中的所有选项。
我正在使用jQuery来选择选项。
在 Internet Explorer 9 中,单击按钮后,浏览器会在所有选项中显示缓慢滚动效果。
示例代码和慢速滚动在 http://jsfiddle.net/willdurman/4b7avgmm/12/
这种效果在最新的Firefox或Chrome中不存在。
如何消除这种缓慢的滚动影响?
要求最初向用户显示未选择任何选项的列表框,然后可以选择单个选项或所有选项。
// Abbreviated list of 10 options
<select id="lb" multiple="multiple">
<option value="0">item number 0</option>
<option value="1">item number 1</option>
<option value="2">item number 2</option>
<option value="3">item number 3</option>
<option value="4">item number 4</option>
<option value="5">item number 5</option>
<option value="6">item number 6</option>
<option value="7">item number 7</option>
<option value="8">item number 8</option>
<option value="9">item number 9</option>
</select>
<input type='button' id='selectAll' value ='Select All'/>
// jQuery to select all options
$(document).ready(function() {
$('#selectAll').click(function(e) {
$("#lb option").prop("selected",true);
});
});
我的最终实现要简单得多。我只是用jQuery隐藏/显示来包装选择过程。
$(document).ready(function() {
$('#selectAll').click(function(e) {
$('#lb').hide();
$("#lb option").prop("selected",true);
$('#lb').show();
});
});
JSFiddle: http://jsfiddle.net/4b7avgmm/17/
我发现,尽管滚动效果在更新、更快的机器上不太明显,但它仍然存在。
经过大量搜索,我发现了这个堆栈溢出问题使用 jquery 动态选择多选列表框中的所有项目。我调整了代码以使用我的示例代码:
var selectAllButton = document.getElementById('selectAll');
var listbox = document.getElementById('lb');
$(selectAllButton).click(function() {
selectAllOptions(listbox);
});
function selectAllOptions(listbox) {
var select = $(listbox);
var clone = select.clone();
$('option', clone).attr('selected', true);
var html = clone.html();
select.html(html);
}
下面是更新的 JSFiddle http://jsfiddle.net/willdurman/4b7avgmm/19/。此方法不会导致在 Internet Explorer 9 中滚动。