jQuery获取各种标签的文本和value值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24192465/article/details/81740880

1、select

<select id="test">
  <option value ="volvo">Volvo</option>
  <option value ="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

获取select 选中的 text :
    $("#test").find("option:selected").text();

获取select选中的 value:
    $("#test").val();

获取select选中的索引:
    $("#test").get(0).selectedindex;

设置select:
设置select 选中的索引:
    $("#test").get(0).selectedindex=index;//index为索引值

设置select 选中的value:
    $("#test").attr("value","normal“);
    $("#test").val("normal");
    $("#test").get(0).value = value;

设置select option项:

    $("#test").append("<option value='value'>text</option>");  //添加一项option
    $("#test").prepend("<option value='0'>请选择</option>"); //在前面插入一项option
    $("#test option:last").remove(); //删除索引值最大的option
    $("#test option[index='0']").remove();//删除索引值为0的option
    $("#test option[value='3']").remove(); //删除值为3的option
    $("#test option[text='4']").remove(); //删除text值为4的option


清空 select:

    $("test").empty();

2、radio

<input type="radio" name="colors" id="red">红色<br>
<input type="radio" name="colors" id="blue">蓝色<br>
<input type="radio" name="colors" id="green">绿色

1.获取选中值,三种方法都可以:

$('input:radio:checked').val();

$("input[type='radio']:checked").val();

$("input[name='colors']:checked").val();

2.设置第一个Radio为选中值:

    $('input:radio:first').attr('checked', 'checked');

或者

$('input:radio:first').attr('checked', 'true');

注:attr("checked",'checked')= attr("checked", 'true')= attr("checked", true)

3.设置最后一个Radio为选中值:

$('input:radio:last').attr('checked', 'checked');

或者

$('input:radio:last').attr('checked', 'true');

4.根据索引值设置任意一个radio为选中值:

$('input:radio').eq(索引值).attr('checked', 'true');索引值=0,1,2....

或者

$('input:radio').slice(1,2).attr('checked', 'true');


5.删除第几个Radio

$("input:radio").eq(索引值).remove();索引值=0,1,2....

如删除第3个Radio:$("input:radio").eq(2).remove();

6.遍历Radio

$('input:radio').each(function(index,domEle){

     //写入代码

});

猜你喜欢

转载自blog.csdn.net/qq_24192465/article/details/81740880