jQuery獲取各種標簽的文本和value值



jQuery獲取各種標簽的文本和value值

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){
 
      //寫入代碼
 
});

3、span

span是塊狀元素,span不存在Value值,<span> 測試內容</span>
要是想取span的內容,$("span").text();

jquery給span賦值

span是最簡單的容器,可以當作一個形式標簽,其取值賦值方法有別於一般的頁面元素。

//賦值

$("#spanid").html(value)

//取值

$("#spanid").text()

在js中

假設我有一個<span id="text"></span>

現在我要單擊一個按鈕后讓span中顯示“Hello,World!”。

<input  id="showBtn" type="button"  value="顯示" onclick="click()"/>

<script type="text/javascript">

function click(){

document.getElementById("text").innerText="Hello,World!";

}

</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM