• select框内容的编辑、修改、添加、删除操作


    1. // 添加  
    2. function col_add() {  
    3.     var selObj = $("#mySelect");  
    4.     var value="value";  
    5.     var text="text";  
    6.     selObj.append("<option value='"+value+"'>"+text+"</option>");  
    7. }  
    8. // 删除  
    9. function col_delete() {  
    10.     var selOpt = $("#mySelect option:selected");  
    11.     selOpt.remove();  
    12. }  
    13. // 清空  
    14. function col_clear() {  
    15.     var selOpt = $("#mySelect option");  
    16.     selOpt.remove();  
    17. }  

    以上方法为jQuery动态添加、删除和清空select。下面是纯js的写法:

    [javascript] view plain copy
     
    1. var sid = document.getElementById("mySelect");  
    2.          
    3. sid.options[sid.options.length]=new Option("text","value");   // 在select最后添加一项  

    其他常用的方法:

    [javascript] view plain copy
     
    1. $("#mySelect").change(function(){//code...});    //select选中项改变时触发  
    2.   
    3. // 获取select值  
    4. var text=$("#mySelect").find("option:selected").text();   //获取Select选中项的Text  
    5. var value=$("#mySelect").val();   //获取Select选中项的Value  
    6. var value=$("#mySelect option:selected").attr("value");   //获取Select选中项的Value  
    7. var index=$("#mySelect").get(0).selectedIndex;   //获取Select选中项的索引值,从0开始  
    8. var index=$("#mySelect option:selected").attr("index");   //不可用!!!  
    9. var index=$("#mySelect option:selected").index();   //获取Select选中项的索引值,从0开始  
    10. var maxIndex=$("#mySelect option:last").attr("index");   //不可用!!!  
    11. var maxIndex=$("#mySelect option:last").index();//获取Select最大索引值,从0开始  
    12. $("#mySelect").prepend("<option value='value'>text</option>");   //Select第一项前插入一项  
    13.   
    14. // 设置select值  
    15. //根据索引设置选中项  
    16. $("#mySelect").get(0).selectedIndex=index;//index为索引值   
    17. //根据value设置选中项  
    18. $("#mySelect").attr("value","newValue");   
    19. $("#mySelect").val("newValue");   
    20. $("#mySelect").get(0).value = value;   
    21. //根据text设置对应的项为选中项  
    22. var count=$("#mySelect option").length;   
    23. for(var i=0;i<count;i++)   
    24. {   
    25.     if($("#mySelect").get(0).options[i].text == text)   
    26.     {   
    27.         $("#mySelect").get(0).options[i].selected = true;   
    28.         break;   
    29.     }   
    30. }   
    31.   
    32. // 清空select  
    33. $("#mySelect").empty();  
  • 相关阅读:
    “5W1H”带你来学习JavaScript
    [windows+cocos2dx]文本类
    server后台TCP连接存活问题
    (七):处理MFC
    Servlet中的request对象、重定向和转发的差别(6)
    ORACLE 存储函数
    【@伏草惟存@】7年系列博文精选
    笔记14:Docker 部署Python项目
    笔记13:Python 和 Elasticsearch 构建简易搜索
    笔试12:Bootstrap知识
  • 原文地址:https://www.cnblogs.com/cx709452428/p/5749152.html
Copyright © 2020-2023  润新知