JQuery 操作對象的屬性值

來源:互聯網
上載者:User

標籤:java   1.7   put   node   介紹   input   代碼   for   val   

通過JQuery去操作前台對象(div,span...)的屬性是很常見的事情,本文就簡單的介紹幾種操作情形。

1):通過屬性值去擷取對象

2):用JQuery去修改對象的屬性值

3):擷取並修改對象的Style的屬性值





<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title> <script src="Scripts/jquery-1.7.1.min.js"></script> <style type="text/css"> .mySpan { color:red; } </style></head><body> <form id="form1" runat="server"> <div> <div id="first_div"> <span class="mySpan" title="first_span" nodeUrl="http://google.com/">first</span> <br /> <span class="mySpan" title="second_span" nodeUrl="http://baidu.com/">second</span> <br /> <span class="mySpan" title="third_span" nodeUrl="http://sina.com/">third</span> </div> <input type="button" name="button" value="Button" onclick="GetObjValueByTitle();" /> </div> </form></body></html>

 

1:通過屬性值擷取對象

基本結構為:物件類別[屬性名稱=‘屬性值‘] 。 例如: span[title=‘first_span‘]

<script type="text/javascript">    function GetObjValueByTitle() {        var obj = $("#first_div span[title=‘first_span‘]");        alert(obj.text());    }</script>

 

2:修改對象的屬性值

用到的便是JQuery提供的attr方法,擷取屬性值的基本結構為:$(obj).attr("屬性名稱");修改屬性值的結構為:$(obj).attr("屬性名稱", "屬性值");

<script type="text/javascript">    function ChangeObjAttrValue() {        var objs = $("#first_div .mySpan");        $.each(objs, function (index, item) {            $(item).attr("title", "haha");            alert($(this).attr("nodeUrl"));  // $(this) == $(item)        });    }</script>

【註:對於具體的對象我們可以隨意添加我們自訂的屬性,並且我們可以通過自訂的屬性名稱擷取對應的屬性值,例如此文中的nodeUrl。】 

 

3:擷取並修改對象的Style屬性值

用到的便是JQuery提供的css方法,擷取style中某個屬性的結構為:$(obj).css("屬性名稱");修改屬性值的結構為:$(obj).css("屬性名稱", "屬性值");

<script type="text/javascript">    function ChangeObjStyleValue() {        var objs = $("#first_div span");        objs.each(function (index, item) {            $(item).css("color", "blue");        });    }</script>

 

由第二條和第三條的對比我們可以簡單的總結:操作對象的屬性值(id, name, title......)我們可以用JQuery的attr方法;操作對象的style屬性(css中的background,color,width,height......)我們可以用JQuery的css方法。

當我們用JQuery去便利集合時,可以用each方法,each的變現形式有兩種:

1):$.each(objs, function(index, item){......});

2):objs.each(function(index, item){......});

JQuery 操作對象的屬性值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.