zoukankan      html  css  js  c++  java
  • JS对select动态添加options操作

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

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

         动态删除select中的某一项option:
           document.getElementById("ddlResourceType").options.remove(indx);  

         动态添加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);//获取文本
        }

    ==============================================================================
    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;

    总结:document.getElementById("元素ID")与jquery中的$("#元素ID")是不等同的,应该用$("#元素ID").get(0)。 get()方法为取得所有匹配的 DOM(document) 元素集合。可用以下方法测试:

    <div id="SAL"></div>

    alert($("#SAL"));  弹出对话框内容为[object,Object]

    alert($("#SAL").get(0));  弹出对话框内容为[object,HTMLDivElement]

    alert(document.getElementById("SAL"));  弹出对话框内容为[object,HTMLDivElement]

    注意:请在FireFox浏览器下进行测式,否则看不到这些变化!

  • 相关阅读:
    linux上TCP connection timeout的原因查找
    AC-BM算法原理与代码实现(模式匹配)
    URPF技术白皮书
    漫谈协同过滤推荐算法
    自己动手写一个推荐系统,推荐系统小结,推荐系统:总体介绍、推荐算法、性能比较, 漫谈“推荐系统”, 浅谈矩阵分解在推荐系统中的应用
    推荐系统的常用算法,选择,漫谈,推荐系统开源软件汇总
    MySQL索引原理及慢查询优化
    深入详解SQL中的Null
    《Gulp 入门指南》 : 使用 gulp 压缩 JS
    Process Explorer
  • 原文地址:https://www.cnblogs.com/SALIN/p/1412714.html
Copyright © 2011-2022 走看看