简体   繁体   中英

Using this inside jQuery filter arrow function

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 .

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.com/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 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM