2016-03-26 16 views
2

我覺得我完全錯過了某些東西,但我無法弄清楚是什麼。我嘗試通過.get()獲取通過索引指定的項目的數據屬性。不過,我似乎無法做到這一點:從get()中找到的元素獲取數據屬性

var int = 1, 
 
\t \t selector = $("a"); 
 
    
 
console.log(selector.get(int)); 
 
console.log(selector.get(int).data("banana")); // Uncaught TypeError: selector.get(...).data is not a function 
 
console.log(selector.get(int)[0].data("banana")); // Uncaught TypeError: selector.get(...).data is not a function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#" data-banana="5">Hello</a> 
 
<a href="#" data-banana="2">there</a>

缺少什麼我在這裏?爲什麼會發生?

回答

1

你必須要在這種情況下使用dataset

console.log(selector.get(int)[0].dataset.banana); 

因爲node對象沒有一個叫其原型data()方法。這是一個屬於jquery對象的函數。

如果你想在這種情況下使用jQuery到一起旅行,那麼你必須使用.eq()

console.log(selector.eq(0).data("banana")); 

基本上.get(1)將提取的第二個元素是從jQuery集合節點對象,而.eq(1)會得到你的第二個元素作爲jQuery對象