2013-07-08 16 views
1
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> 
    </script> 
<a href="http://www.google.com" id="aGoogle1">Google Link</a> 
<script type="text/javascript"> 
$(function() 
{ 

     console.log($('a[href="http://www.google.com"]')); 
}); 
</script> 

在chrome-> console中,我可以看到$('a[href="http://www.google.com"]')返回所選元素,我可以看到它具有以下屬性:id:「aGoogle1」。所以我的問題是:如何在jquery中輸出所選元素的屬性?

如何輸出屬性,例如編號,我試過$('a[href="http://www.google.com"]'.id),但它不起作用?

回答

1

您可以使用attr()prop()來獲取元素的屬性。但是兩者之間有一些差異。檢查attr() Vs prop()。您可以通過

$('a[href="http://www.google.com"]').attr('id'); 

$('a[href="http://www.google.com"]').prop('id'); 
0

使用attr()來獲取或設置屬性

alert($('a[href="http://www.google.com"]').attr('id')); 

這將讓所選元素的ID

0

Ue的attr

$('a[href="http://www.google.com"]').attr('id'); 

prop

$('a[href="http://www.google.com"]').prop('id'); 
0
$('a[href="http://www.google.com"]'.id) 

此代碼試圖訪問字符串對象'a[href="http://www.google.com"]'的財產id訪問ID;結果是undefined。之後你將其包裝在一個jQuery對象中。這個結果是一個空的jQuery集合。

你需要總是從這裏開始:

$('a[href="http://www.google.com"]') 

然後使用jQuery的功能做你所需要的。在你的情況下,你希望訪問錨元素的屬性,所以你使用prop()

$('a[href="http://www.google.com"]').prop('id') 
相關問題