javascript - Using this inside jQuery filter arrow function - Stack Overflow

When having a code like this:$elements.filter(() => {console.log(this);will be the parent scope&

When having a code like this:

$elements.filter(() => {
    console.log(this); // will be the parent scope's "this"
});

you are not able to get the element that should be filtered. So you would need to use a normal function, like:

$elements.filter(function(){
    console.log($(this)); // will be the element to filter
});

Is there any other way instead of using normal functions? I know for click events you can use event.currentTarget, but there is no event parameter in filter.

When having a code like this:

$elements.filter(() => {
    console.log(this); // will be the parent scope's "this"
});

you are not able to get the element that should be filtered. So you would need to use a normal function, like:

$elements.filter(function(){
    console.log($(this)); // will be the element to filter
});

Is there any other way instead of using normal functions? I know for click events you can use event.currentTarget, but there is no event parameter in filter.

Share Improve this question asked Mar 15, 2016 at 11:49 dudedude 6,10611 gold badges55 silver badges85 bronze badges 1
  • TLDR: (idx, node) => console.log( $(node) ); // replace 'this' with 'node' – Justin Commented Jun 3, 2020 at 2:39
Add a ment  | 

1 Answer 1

Reset to default 10

While you don't get the reference to the expected this, it's possible to use the arguments supplied by the anonymous function, the index and the DOM node, in that order:

$elements.filter((index, node) => {
  console.log(node);
});

let $elements = $('li');

$elements.filter((index, node) => {
  console.log(node);
});
li {
  width: 50%;
  border: 2px solid #000;
}
li.red {
  border-color: red;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="red"></li>
  <li class="red"></li>
  <li class="red"></li>
  <li class="red"></li>
  <li></li>
  <li class="red"></li>
  <li class="red"></li>
  <li></li>
  <li class="red"></li>
  <li></li>
  <li class="red"></li>
  <li class="red"></li>
  <li class="red"></li>
  <li class="red"></li>
  <li></li>
  <li></li>
  <li class="red"></li>
  <li class="red"></li>
  <li class="red"></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

JS Fiddle demo;

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744145472a4560400.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信