zoukankan      html  css  js  c++  java
  • Html下拉框的定义以及JS、Jquary取值、添加和移除

    现在有一id=test的下拉框,怎么拿到选中的那个值呢?

    分别使用javascript原生的方法和jquery方法

    <select id="test"  name="" multiply="multiply" size="10">   //multiply设置可以多行显示,size设置默认显示多少行。
      <option   value="1">text1</option>   
      <option   value="2">text2</option>   
     </select>

    code:

    一:javascript原生的方法

      1:拿到select对象: var  myselect=document.getElementById("test");

      2:拿到选中项的索引:var index=myselect.selectedIndex ;             // selectedIndex代表的是你所选中项的index

      3:拿到选中项options的value:  myselect.options[index].value;

      4:拿到选中项options的text:  myselect.options[index].text;

    二:jquery方法(前提是已经加载了jquery库)

    1:var options=$("#test option:selected");  //获取选中的项

    2:alert(options.val());   //拿到选中项的值

    3:alert(options.text());   //拿到选中项的文本

    三:Js实现下拉框选项的新增和移除

    1:拿到select对象: var  myselect=document.getElementById("test");

    2:新增:myselect.options.Add(new options("text","value"));

    3:移除:myselect.options.Remove(myselect.options[myselect.selectedIndex]);

    4:清空:myselect.empty();

  • 相关阅读:
    Vue生命周期(转)
    Gulp的简单使用
    webpack的简单使用
    面试----手写正则表达式
    面试----你可以手写一个promise吗
    baidu.com跳转www.baidu.com
    php 操作时间、日期类函数
    php操作文件类的函数
    sphinx搜索 笔记
    bash下输入命令的几个常用快捷键
  • 原文地址:https://www.cnblogs.com/xiaoerlang90/p/4314312.html
Copyright © 2011-2022 走看看