从使用 get() 找到的元素中获取数据属性

Get data-attribute from element that's found with get()

我觉得我完全错过了什么,我不知道是什么。我尝试通过 .get() 获取使用索引指定的项目的数据属性。但是,我似乎做不到:

var int = 1,
  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>

我在这里错过了什么?为什么会这样?

您必须在这种情况下使用 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 对象