2010-11-28 51 views
0

如何在jQuery中選擇「根」級元素的屬性?在jQuery中選擇根元素的屬性

下不工作(返回未定義):

jQuery(document).ready(function() { 

    somehtml = "<a href='http://example.com'>An example</a>"; 
    theurl = jQuery('a',somehtml).attr('href'); 
    alert(theurl); 

} 

任何想法,我缺少的是什麼?我敢肯定,這是關於根級別的元素明顯的東西...

提前許多感謝, GAV株系

回答

3

你可以這樣做:

jQuery(document).ready(function() { 

    somehtml = "<a href='http://example.com'>An example</a>"; 
    theurl = $(somehtml).attr('href'); 
    alert(theurl); 

}); 

我所做的就是建立一個jQuery對象了的HTML,然後直接訪問attr()函數。

+0

這個例子是正確的。將HTML放入jQuery對象中,可以製作HTML根節點的jQuery對象。你無法找到其中的某些東西,它本身就是你以後的事情。 – Orbling 2010-11-28 20:17:54