瞭解jQuery技巧來提高你的代碼(個人覺得那個jquery的手冊很不錯)

來源:互聯網
上載者:User


2.測試jQuery封裝集是否包含某些元素
  如果你想測試一下某個jQuery封裝集中是否包含某些元素,你首先可以嘗試使用驗證首個元素是否存在:
複製代碼 代碼如下:
if($(selector)[0]){...}
// 或者這樣
if($(selector).length){...}

來看看這個例子:
複製代碼 代碼如下:
//例子.如果你的頁面有以下html代碼
<ul id="shopping_cart_items">
<li><input class="in_stock" name="item" type="radio" value="Item-X" />Item X</li>
<li><input class="unknown" name="item" type="radio" value="Item-Y" />Item Y</li>
<li><input class="in_stock" name="item" type="radio" value="Item-Z" />Item Z</li>
</ul>
<pre escaped="true" lang="javascript">...
//這個if條件將返回true,因為我們有兩個
// input域匹配了選取器,所以<statement>代碼將會執行
if($('#shopping_cart_items input.in_stock')[0]){<statement>}

3.從jquery.org讀取jQuery最新版本
你可以使用這句代碼讀取jQuery的最新版本的代碼檔案。

<script src="http://code.jquery.com/jquery-latest.js"></script>
你可以使用這個方法來調用最近版本的jQuery架構,當然,你還可以使用下面這個代碼從ajax.googleapis.com調用同樣的最新版本jQuery:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
type="text/javascript"></script>
4.儲存資料
  使用data方法可以避免在DOM中儲存資料,有些前端開發er喜歡使用HTML的屬性來儲存資料:
複製代碼 代碼如下:
$('selector').attr('alt', 'data being stored');
//之後可以這樣讀取資料:
$('selector').attr('alt');

  使用”alt”屬性來作為參數名儲存資料其實對於HTML來說是不符合語義的,我們可以使用jQuery的data方法來為頁面中的某個元素儲存資料:
複製代碼 代碼如下:
$('selector').data('參數名', '要儲存的資料');
//之後這樣取得資料:
$('selector').data('參數');

  這個data方法能讓你自己明明資料的參數,更語義更靈活,你可以在頁面上的任何元素儲存資料資訊。如果想瞭解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.