在jQuery每个循环中获取元素的父元素[复制](Get parent of element in jQuery each loop [duplicate])

编程入门 行业动态 更新时间:2024-10-27 20:28:12
在jQuery每个循环中获取元素的父元素[复制](Get parent of element in jQuery each loop [duplicate])

这个问题在这里已经有了答案:

箭头函数与函数声明/表达式:它们是等价的还是可交换的? 2个答案

我完全沉迷于此。 我在页面上有三个元素,其中有一类.topic-link 。

<div id="parent1"> <a href="#" class="topic-link"></a> </div> <div id="parent2"> <a href="#" class="topic-link"></a> </div> <div id="parent3"> <a href="#" class="topic-link"></a> </div>

我可以运行$('.topic-link').eq(0).parent(); 在JS控制台中并返回正确的父代。 但是当我遍历它们时,每次都会得到一个空对象。

$('.topic-link').each( () => { console.log($(this).parent()); }); // returns 3 empty objects

This question already has an answer here:

Are 'Arrow Functions' and 'Functions' equivalent / exchangeable? 1 answer

I'm completely stumped on this. I have three elements on the page with a class of .topic-link.

<div id="parent1"> <a href="#" class="topic-link"></a> </div> <div id="parent2"> <a href="#" class="topic-link"></a> </div> <div id="parent3"> <a href="#" class="topic-link"></a> </div>

I can run $('.topic-link').eq(0).parent(); in the JS console and get the correct parent returned. But when I iterate over them I get an empty object each time.

$('.topic-link').each( () => { console.log($(this).parent()); }); // returns 3 empty objects

最满意答案

箭头函数没有自己的this所以你有什么等于

$('.topic-link').each(function () { console.log($(this).parent()); });

在你的情况下, this是window (或document或任何取决于范围调用),没有父节点

Arrow functions don't have their own this so what you have is not equivalent to

$('.topic-link').each(function () { console.log($(this).parent()); });

In your case this is window (or document or whatever depending on scope it is called in) which has no parent dom node

更多推荐

本文发布于:2023-07-16 12:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128517.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   parent   jQuery   duplicate   loop

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!