日期:2014-05-16  浏览次数:20403 次

JS select option 元素的大批量添加

最近项目需要这么一个很蛋疼的需求。

我都想知道、干嘛要添加这么数据到select里面去呢、疯了吗(测试数据1W多条)?

结果是老总说必须加、功能没实现是我们的问题、他们用不用得了、是他们的问题。

需求是这样的:


用户选择完毕还可以删除所选的选项:


一两百条、添加那是毛毛雨、分分钟搞定啊!

但是数据多了的时候就老火了、浏览器直接假死、白屏、下面是最初的添加方法:

页面按钮:

<select name="sm_careReceivers" id="sm_careReceivers"
multiple="multiple" size="8" 
style="width: 355px; color: #006CAD;">
</select>
<button type="button" onclick="returnSelectCustomerInfo();">确定</button>

JS方法:

var obj = $("#sm_careReceivers");
var count = $("#sm_careReceivers option").length;
for(var o in json){ 
	listText = json[o].name;
	listValue = json[o].phone;
	listTypeValue = json[o].cusid; 
	listTypeText = json[o].text;   
	flag = true;	  
	//判断是否已存在				
	for ( var i = 0; i < count; i++) {
		if (obj.get(0).options[i].value == listText + "/"
				+ listValue + "/" + listTypeValue) {
			flag = false;
			break;
		}  
	}
	//给控件赋值
	if (flag) {
		if (listText == "") {   
			obj.append("<option value='" + "佚名" + "/"
					+ listValue + "/" + listTypeValue + "'>"
					+ "佚名" + "/" + listValue + "/" + listTypeText
					+ "</option>");
		} else {
			obj.append("<option value='" + listText + "/"
					+ listValue + "/" + listTypeValue + "'>"
					+ listText + "/" + listValue + "/" + listTypeText
					+ "</option>");  
		}
	}
}

以下是几种优化方案:

  • 第一种:

              采用字符拼接方式、先把所有的option全部组装成字符串、然后在渲染页面:

var obj = $("#sm_careReceivers");
var count = $("#sm_careReceivers option").length;
var sHtmlTest = "";
for(var o in json){ 
	listText = json[o].name;
	listValue = json[o].phone;
	listTypeValue = json[o].cusid; 
	listTypeText = json[o].text;   
	flag = true;	  
	//判断是否已存在				
	for ( var i = 0; i < count; i++) {
		if (obj.get(0).options[i].value == listText + "/"
				+ listValue + "/" + listTypeValue) {
			flag = false;
			break;
		}  
	}
	//给控件赋值
	if (flag) {
		if (listText == "") {   
			sHtmlTest+="<option value='" + "佚名" + "/"
					+ listValue + "/" + listTypeValue + "'>"
					+ "佚名" + "/" + listValue + "/" + listTypeText
					+ "</option>";
		} else {
			sHtmlTest+="<option value='" + listText + "/"
					+ listValue + "/" + listTypeValue + "'>"
					+ listText + "/" + listValue + "/" + listTypeText
					+ "</option>";  
		}
	}
}
obj.append(sHtmlTest); 

  • 第二种:

             采用文档碎片(该方法不支持火狐——主要是innerText属性)

var obj = $("#sm_careReceivers");
var count = $("#sm_careReceivers option").length;
var warp = document.createDocumentFragment();
for(var o in json){ 
	listText = json[o].name;
	listValue = json[o].phone;
	listTypeValue = json[o].cusid; 
	listTypeText = json[o].text;   
	flag = true;	  
	//判断是否已存在				
	for ( var i = 0; i < count; i++) {
		if (obj.get(0).options[i].value == listText + "/"
				+ listValue + "/" + listTypeValue) {
			flag = false;
			break;
		}  
	}
	//给控件赋值
	if (flag) {
		var objOption = documen