js

作者: 趁年轻拼一拼 | 来源:发表于2018-07-22 22:52 被阅读0次

读取并修改元素的内容

假设两个select元素,分别保存备选地区列表和选中地区列表
实现两选择框之间选项的交换:
包括:当个选中项左右移动
多个选中项左右移动
全左移和全右移
要求:两个select中的地区都要按照名称首字母排序

<select id="unsel" size="8" multiple>
        <option>Argentina</option>
        <option>Brazil</option>
        <option>Canada</option>
        <option>Chile</option>
        <option>China</option>
        <option>Cuba</option>
        <option>Denmark</option>
        <option>Egypt</option>
        <option>France</option>
        <option>Greece</option>
        <option>Spain</option>
</select>
    <div>
        <button onclick='move(this)'>&gt;&gt;</button>
        <button onclick='move(this)'>&gt;</button>
        <button onclick='move(this)'>&lt;</button>
        <button onclick='move(this)'>&lt;&lt;</button>
    </div>
<select id="sel" size="8" multiple>
</select>

1)将unsel元素中的所有国家名称填充到unselCts中

unsel的内容去掉开头和结尾的空字符,再掐头去尾,按?切割

unselCts=
  unsel.innerHTML
       .replace(/^\s+|\s+$/g,"")
       .slice(8,-9)
       .split(/<\/option>\s*<option>/);

2)判断btn的内容

是>>,就将unselCts拼接到selCts结尾,再保存回selCts中

function move(btn){
  switch(btn.innerHTML){
    case "&gt;&gt;":
      selCts=selCts.concat(unselCts);
      unselCts=[];//将unselCts清空
      break;
是<<,就将selCts拼接到unselCts结尾,再保存回unselCts中

    case "&lt;&lt;"://
      unselCts=unselCts.concat(selCts);
      selCts=[];//将selCts清空
      break;
是>, 查找id为unsel下的所有option,保存在变量opts中

    case "&gt;":
      var opts=document.querySelectorAll(
        "#unsel>option"
      );
反向遍历opts中每个opt

    for(var i=opts.length-1;i>=0;i--){
        for(var i=0;i<opts.length;i++){
        //如果当前opt的selected为true//为什么用true判断
        if(opts[i].selected){
          //删除unselCts数组中当前位置的元素,再将删除的元素拼接到selCts中
          selCts.push(unselCts.splice(i,1));
        }
    }
    break;
是<,就查找id为sel下的所有option,保存在变量opts中
    case "&lt;":
      var opts=document.querySelectorAll(
        "#sel>option"  
      );
反向遍历opts中每个opt

      for(var i=opts.length-1;i>=0;i--){
        for(var i=0;i<opts.length;i++){
        //如果当前opt的selected为true
        if(opts[i].selected){
          //删除selCts数组中当前位置的元素,再将删除的元素拼接到unselCts中
          unselCts.push(selCts.splice(i,1));
        }
      }
  }

将unselCts按国家名称升序排列

unselCts.sort();
将selCts按国家名称升序排序

selCts.sort();
查找id为unsel的元素,保存在unsel中

var unsel=document.getElementById("unsel");
将unselCts数组的内容更新到unsel元素中

 updateSel(unselCts,unsel);
查找id为sel的元素,保存在sel中

  var sel=document.getElementById("sel");
将selCts数组的内容更新到sel元素中

  updateSel(selCts,sel);
}

设置sel的内容为:arr按?拼接,补上开头和结尾

function updateSel(arr,sel){
  sel.innerHTML=("<option>"+
    arr.join("</option><option>")
    +"</option>");
}

相关文章

网友评论

      本文标题:js

      本文链接:https://www.haomeiwen.com/subject/bggrmftx.html