在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 objectsThis question already has an answer here:
Are 'Arrow Functions' and 'Functions' equivalent / exchangeable? 1 answerI'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
更多推荐
发布评论