zoukankan      html  css  js  c++  java
  • JS对select动态添加options操作[IE&FireFox兼容]

    做一个项目,遇到了要动态调整 select 选项的情况,就baidu了一下,发现了一篇与本文同名的帖子.

    但是呢,那个帖子里的方法并不兼容.  

    附原文:

    <select id="ddlResourceType" onchange="getvalue(this)">
    </select>

       动态删除select中的所有options:
           document.getElementById("ddlResourceType").options.length=0;

         动态删除select中的某一项option:
           document.getElementById("ddlResourceType").options.remove(indx);
      
    //就是这句不兼容了,Firefox是不懂 remove 这个方法的,所以会报错了,当然也移除不了了

        动态添加select中的项option:
           document.getElementById("ddlResourceType").options.add(new Option(text,value));

       上面在IE和FireFox都能测试成功,希望以后你可以用上。
    其实用标准的DOM操作也可以,就是document.createElement,appendChild,removeChild之类的。

        取值方面
        function getvalue(obj)
         {
             var m=obj.options[obj.selectedIndex].value
             alert(m);//获取value
             var n=obj.options[obj.selectedIndex].text
             alert(n);//获取文本
         }

    后来,发现这篇文章末端的那几句话,觉得可以用dom试试,嗯,果然可行.

    var sObj=document.getElementById("ddlResourceType");

    sObj.removeChild(sObj.options[indx]);

    这样,上面这句就做到兼容了.

    其他的代码都没有问题,可以兼容. 

    1 检测是否有选中
    if (objSelect.selectedIndex > - 1 ) {
    // 说明选中
    } else {
    // 说明没有选中
    }

    2 删除被选中的项
    objSelect.options[objSelect.selectedIndex] = null ;

    3 增加项
    objSelect.options[objSelect.length] = new Option( " 你好 " , " hello " );

    4 修改所选择中的项
    objSelect.options[objSelect.selectedIndex] = new Option( " 你好 " , " hello " );

    5 得到所选择项的文本
    objSelect.options[objSelect.selectedIndex].text;

    6 得到所选择项的值
    objSelect.options[objSelect.selectedIndex].value;

    转至:http://lulitianyu.blog.163.com/blog/static/91360302007112710574596/

  • 相关阅读:
    Identity Server4 基础应用(一)Client Credentials
    AX2012 form displays unusually because of native resolution issues(由于本机高分辨率问题导致AX2012界面显示异常)
    AX视图View中添加静态方法
    AX2012导Demo数据
    AX多线程编译
    C# ListView用法详解 很完整
    用 C# 如何判断数据库中是否存在一个值
    ASCII码对照表
    C#中Chart的简单使用(柱状图和折线图)
    使用Filezilla Server配置FTP服务器
  • 原文地址:https://www.cnblogs.com/load/p/2267207.html
Copyright © 2011-2022 走看看