在H5頁面中用js實現選擇器中數據過多時,進行分組選擇
項目中有個進行區服選擇需求,因爲有些區服數組過長,一個選擇器進行選擇需要滑動時間太久。
所以對數據先做分組處理,然後把選擇項進行分組顯示
下面是相關代碼`//填充區服
function FillAreaService(data) {
console.log("fill the list");
var str = '';
var multipleSelect = document.getElementById("multipleSelect");
var singleSelect = document.getElementById("singleSelect");
if(data.length > 100) {
multipleSelect.className = "multipleSelect";
singleSelect.className = "none";
var group = Math.ceil(data.length / 100);
_splitedData = this.Packet(data);
// console.log("##### splited data", _splitedData);
for(var i = 0; i < group; i++) {
$("#groupId").append('<option id="groupOption" value="' + i + '">' + (i * 100 + 1) + "--" + (i + 1) * 100 + '</option>');
}
} else {
$.each(data, function(i, v) {
str += '<option value="' + v['server_id'] + '">' + v['server_name'] + "(" + v['server_id'] + ")" + '</option>';
});
$('#serverId').append(str);
}
}
//填充區服的單個條目
function FillAreaItem(groupIndex) {
// console.log("@@@@@ fill the area server item", groupIndex);
$('.groupItemSelect').empty().append('<option value="">--請選擇--</option>');
var _data = _splitedData[groupIndex];
var str = '';
$.each(_data, function(i, v) {
str += '<option value="' + v['server_id'] + '">' + v['server_name'] + "(" + v['server_id'] + ")" + '</option>';
});
$('.groupItemSelect').append(str);
// console.log("####### server id", $("#serverId"));
}
//數據分組
function Packet(_data) {
var allDataArray = new Array();
var group = Math.ceil(_data.length / 100);
for(var i = 0; i < group; i++) {
var tempArray = new Array();
for(var j = i * 100; j < (i + 1) * 100 && j < _data.length; j++) {
tempArray.push(_data[j])
}
allDataArray.push(tempArray);
}
return allDataArray;
}
因爲當數數據少的時候就不分組,html頁面部分代碼如下
```
<p class="singleSelect" id="singleSelect">
<span class="rechargeL">區服<span style="color: red">*</span>:</span>
<select name="serverId" class="" id="serverId">
<option value="">--請選擇--</option>
</select>
</p>
<p class="multipleSelect none" id="multipleSelect">
<span class="rechargeL">區服<span style="color:red">*</span>:</span>
<select name="serverId" class="groupSelect" id="groupId">
<option value="">--請選擇--</option>
</select>
<select name="serverId" class="groupItemSelect" id="serverId">
<option value="">--請選擇--</option>
</select>
</p>
```
獲的當前選項的數據代碼如下。
serverId = $('select:visible[id="serverId"]').val();
serverName = $('select:visible[id="serverId"] option:selected').html();
記錄一下平時遇到的問題
也算是拋磚引玉,希望能得到大佬的點播