1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > JS级联下拉列表 DOM编程

JS级联下拉列表 DOM编程

时间:2019-02-21 13:13:05

相关推荐

JS级联下拉列表 DOM编程

使用DOM编程,在网页中完成简单的JS级联下拉列表。

先整理常用的DOM操作:

创建新节点

document.createElement(‘div’)document.createAttribute(‘class’);document.createTextNode(‘文本’) e.innerHTML document.createComment(‘注释内容’); document.createDocumentFragment();

把新节点添加到元素树

e.setAttributeNode(newAttr)e.appendChild(newTxt/newElement/fragment)e.insertBefore(newTxt/newElement/fragment, existingChild)

删除已有节点

var deletedChild = parentNode.removeChild( existingChild );

替换已有节点

var replacedChild = parentNode.replaceChild( newChild, existingChild );

删除属性节点

element.removeAttribute(‘属性名’);

element.removeAttributeNode(attrNode);

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><title></title><style type="text/css">*{margin:0; padding:0;}</style></head><body><h2>省市级联下拉</h2><select id="provinces" onchange='changeCity(this.value)'><option value="-1">--请选择--</option></select><select id="citys"><option value="-1">--请选择--</option></select><script>var ps = ['北京市','天津市','河北省'];var cs = [['东城区','西城'],['河东区','和平区'],['廊坊市','石家庄市','唐山市']];var fragment = document.createDocumentFragment();for(var i=0; i<ps.length; i++){var option = document.createElement('option');option.setAttribute('value', i);option.innerHTML = ps[i];fragment.appendChild(option);}document.getElementById('provinces').appendChild(fragment);//添加地级市function changeCity(pno){if(pno==-1){return;}//删除下拉框中已有的地级市var cSelect = document.getElementById('citys');while(cSelect.children.length>0){cSelect.removeChild(cSelect.lastElementChild);}/*cSelect.innerHTML = '';*///再添加当前指定省份中的地级市var cityArr = cs[pno];var fragment = document.createDocumentFragment();for(var i=0; i<cityArr.length; i++){var option = document.createElement('option');option.setAttribute('value', i);option.innerHTML = cityArr[i];fragment.appendChild(option);}cSelect.appendChild(fragment);}</script></body></html>

代码可直接实现如图效果。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。