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
.
-
TLDR:
(idx, node) => console.log( $(node) );
// replace 'this' with 'node' – Justin Commented Jun 3, 2020 at 2:39
1 Answer
Reset to default 10While 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条)