zoukankan      html  css  js  c++  java
  • select联动遇到的问题

    今天写了个select下拉联动,记录下过程中遇到的问题。

    dom部分

    // 拿到选中项的索引

    myselect.selectedIndex

    // 拿到选中项的text/value

    myselect.options[index].text;

    删除元素下的所有子元素

    常用三种

    //方法一:
    while(selectObj.firstChild) {
      selectObj.removeChild(selectObj.firstChild);
    }
    
    //方法二:
    selectObj.innerHTML = "";
    
    //方法三:
    for(var i=optionNodes.length-1;i>=0;i--) {
      selectObj.removeChild(selectObj.lastChild);
    }

    最后上个select联动的demo代码

    点击城市显示对应的大学列表

          <select name="city" id="city">
            <option value="1">北京</option>
            <option value="2">上海</option>   
            <option value="3">南京</option>   
            <option value="4">杭州</option>              
          </select>
          <select name="school" id="school">
            <option value="1">清华大学</option>   
            <option value="2">北京大学</option>   
            <option value="3">中国人民大学</option>
            <option value="4">北京师范大学</option>
          </select>
        const city = document.getElementById("city");
        const school = document.getElementById("school");
    
        const cityArr = ["北京", "上海", "南京", "杭州"];
        const schoolArr = [
          ["清华大学", "北京大学", "中国人民大学", "北京师范大学"],
          ["复旦大学", "上海交通大学", "同济大学", "华东师范大学"],
          ["南京大学", "东南大学", "中国药科大学", "河海大学"],
          ["浙江大学", "浙江工业大学", "杭州电子科技大学", "浙江工商大学", "a"]
        ];
        
        city.addEventListener("change", () => {
          // 拿到选中项的索引 myselect.selectedIndex
          let cityIndex = city.selectedIndex;
          for (let i = 0; i < cityArr.length; i++) {
            // 拿到选中项的文本  myselect.options[index].text;
            if (city.options[cityIndex].text === cityArr[i]) {
              // 删掉所有子元素
              while (school.firstChild) {
                school.removeChild(school.firstChild);
              }
              // 把索引对应的学校数组数据加入到页面
              for (let y = 0; y < schoolArr[i].length; y++) {
                let option = document.createElement("option");
                option.innerText = schoolArr[i][y];
                school.appendChild(option);
              }         
            }
          }
        })
  • 相关阅读:
    mybatis Column 'XXX' in where clause is ambiguous 错误
    IDEA 代码提示不区分大小写
    接口安全问题
    spring 事务问题
    js问题: is not a function
    Uncaught TypeError: form.attr is not a function 解决办法
    springmvc 跳转页面或者返回json
    ajax 跳转页面时添加header
    maven工程 添加本地jar依赖
    mysql 创建备份表
  • 原文地址:https://www.cnblogs.com/gr07/p/7976454.html
Copyright © 2011-2022 走看看