zoukankan      html  css  js  c++  java
  • select设置innerHMTL

    select控件在标准浏览器下可以直接innerHTML设置内容,IE则不行。

    HTML结构:

    <form name="form1">
        <select name="select1"></select>
    </form>

    先看直接使用select.innerHTML

    var form = document.forms["form1"];
        var select = form["select1"];
        select.innerHTML = '<option value="1">1</option>';

    运行发现标准浏览器如chrome, firefox运行正常,DOM树为

    IE(678)全家都呵呵了:

    原因在于IE使用innerHTML给select赋值时会根据/^<wd['" ]>&/(尖括号中间的字母、数字,引号,空格)匹配的字符都干掉,无力吐槽。

    2种解决思路

    1、使用select的outerHTML或者父级的innerHMTL

    var select = document.forms["form1"]["select1"];
    select.outerHTML = '<select name="select1"><option value="1">1</option></select>';

    outerHMTL IE系列和chrome是支持的,新版的FireFox也支持,国内Firefox浏览器份额低的可以忽略不计。如果嫌弃outerHTML,当然可以换innerHTML

    document.forms["form1"].innerHTML = '<select name="select1"><option value="1">1</option></select>';

      简单暴力

    2、使用new Option创建select的options,这是比较推荐的方法。

        var form = document.forms["form1"];
        var select = form["select1"];
        select.options.add(new Option("text", "value")); // 或 select.add(new Option("text", "value"))

      new Option创建一个option对象实例,依次接受text,value两个参数,text为option的文本值,value即为option的value值。

    发散思维,几种常见的option操作做个汇总:

        var form = document.forms["form1"];
        var select = form["select1"];
        
        // 增加
        select.options.add(new Option("text1", "value1")); // 或 select.add(new Option("text1", "value1"))
        select.options.add(new Option("text2", "value2")); // 或 select.add(new Option("text2", "value2"))
        
        // 删除选中项,也可指定删除
        var index = select.options.selectedIndex;
        select.options.remove(select.index); // 或 select.remove(select.index)
        
        // 全删
        select.options.length = 0;
    
        // 改text
        select.options[select.selectedIndex].text = "text3"; 
        // 改value
        select.options[select.selectedIndex].value = "value3";
        // 同时修改text | value
        select.options[select.selectedIndex] = new Option("text3", "value3");
        
        //
        var text = select.options[select.selectedIndex].text;
        var value = select.options[select.selectedIndex].value;
  • 相关阅读:
    【leetcode】Binary Search Tree Iterator
    【leetcode】Palindrome Partitioning II
    【leetcode】Best Time to Buy and Sell Stock III
    【leetcode】Best Time to Buy and Sell Stock II
    【leetcode】Longest Consecutive Sequence
    【leetcode】Factorial Trailing Zeroes
    【leetcode】Simplify Path
    【leetcode】Generate Parentheses
    【leetcode】Combination Sum II
    【leetcode】Combination Sum
  • 原文地址:https://www.cnblogs.com/mr189/p/3698242.html
Copyright © 2011-2022 走看看