简体   繁体   English

在jQuery过滤器箭头内部使用此函数

[英]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 . 我知道对于点击事件,您可以使用event.currentTarget ,但是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: 虽然没有获得对预期this的引用,但是可以按以下顺序使用匿名函数,索引和DOM节点提供的参数:

$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 ; JS小提琴演示 ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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