通过JS和JQ操作元素总结

1、文本框:
<input type = "text" name = "inputValue" id = "text1" />
 
JS: 
    document.getElementById("text1").value = "some value"
    var aaa = document.getElementById("text1").value
 
JQ: 
    $("#text1").val("some value");
    var aaa = $("#text1").val();
 
2、下拉列表:
<select name = "selectValue" id = "select1" >
    <option value = "1">test1</option>
    <option value = "2">text2</option>
    <option value = "3">text3</option>
</select>

JS:     
    获取选中列表的value(不是选项值): document.getElementById("select1").value
 
    获取选中列表的值:
    方法一:select1.options[selectValue.selectedIndex].text;
    方法二:
    var select1=document.getElementById("select1");
    for(var i=0;i<select1.length;i++)   
    {   
      if(select1.options[i].selected)   
      {   
        var aaa = select1.options[i].text;   
      }
    }
    另外,可以通过select1.getElementsByTagName("option").length;来获取下拉列表的个数。
 
JQ: 
    获取选中value对应的文本值:
        $("#select1>option:selected").text();
        $("#select1").find("option:selected").text();
    获取选中列表的value: 
        $("#text1").val();
 
    设置选中第一个值:
        $("#select1>option:eq(0)").attr("selected", true);
    设置value值:
        $("#select1").val("2");
    设置文本值:
        $("#select1>option:contains('text2')").attr("selected", true);
 
 
3、radio控件:
    <input id = "rdoMan" type = "radio" name = "sex" value = "1" checked = "checked"/><label for = "rdoMan">男</label>
    <input id = "rdoFemale" type = "radio" name = "sex" value = "2"/><label for = "rdoFemale">女</label>
    
    JS:
        
        设置值:
                document.getElementById("rdoFemale").checked = true;
                document.getElementsByName("sex")[1].checked = true;
        获取值:var aaa = select1.value;
 
    JQ:
        设置值:$("[name = 'sex'][value = '2']").attr("checked", true);
        获取值:$("[name = 'sex']").val();
posted @ 2015-09-30 13:49  直来直往  阅读(439)  评论(0编辑  收藏  举报