用javascript动态整体替换修改下拉列表option的内容

<html>

<script>
function test() {
var childRet = document.getElementById('sel');
for (var i = childRet.childNodes.length-1; i >= 0; i--) {
childRet.removeChild(childRet.childNodes.item(i));
}


var tmpRet = {
"DATA": {"name": "saj", "pass": "abc", "X": "X"}
};
var ret = document.createDocumentFragment();
var tmpObj = tmpRet["DATA"];
for (var key in tmpObj)
{
if(key != "X") {
var newop = document.createElement("option");
newop.id = key;
newop.value = key;
newop.appendChild(document.createTextNode(tmpObj[key]));
ret.appendChild(newop);
}
}

document.getElementById('sel').appendChild(ret);

   }


</script>
<body>
<form>
<select id="sel">
<option>aa</option>
<option>bb</option>
</select>
<input type="button" onclick="test()" value="childNodes"/>
</form>
</body>
</html>

以上已经在IE测试通过
原来select内容是aa,bb,点按钮后内容变成saj,abc

document.createDocumentFragment
添加节点的时候使用
对于少量的更新,可以不使用
然而,当要添加大量数据时,如果逐个添加这些节点,这个过程有可能会十分缓慢。为解决这个问题,可以创建一个文档碎片,把所有的新节点附加其上,然后把文档碎片的内容一次性添加到document中。

假设你想创建十个新段落。你可能这样写
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
</HEAD>
<script defer>
var arrText = ["1", "2", "3","4", "5","6","7","8","9","10"];
for ( var i = 0; i < arrText.length ;i++ )
{
var op = document.createElement("p");
var oText = document.createTextNode(arrText[i]);
op.appendChild(oText);
document.body.appendChild(op);
}
</script>
<BODY>
</BODY>
</HTML>


这段代码运行良好,但问题是它调用了十次document.body.appendChild(),每次要产生一次页面刷新。这时,文档碎片会更高效:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
</HEAD>
<script defer>
var arrText = ["1", "2", "3","4", "5","6","7","8","9","10"];
var oFrag = document.createDocumentFragment();
for ( var i = 0; i < arrText.length ;i++ )
{
var op = document.createElement("p");
var oText = document.createTextNode(arrText[i]);
op.appendChild(oText);
oFrag.appendChild(op);
}
document.body.appendChild(oFrag);
</script>
<BODY>
</BODY>
</HTML>

你可能感兴趣的:(JavaScript,html,IE)