Jquery,函数内的“this”总是返回文档

Pun*_*Wai 2 jquery pug

$("#oulist li").filter(() => {
  console.log(this);
}).css("background-color", "red")
Run Code Online (Sandbox Code Playgroud)

您好,每当我尝试使用此功能时,它总是以文档形式返回。我不确定这是否与 pug.js 有关。

Jim*_*mex 7

您的问题是您正在使用较新的 ES6 箭头函数,但它没有this按您的预期使用。更改() => { }为传统function() {}符号以查看差异。在此处阅读有关箭头函数的更多信息。

您还忘记return this;返回<li>元素.css();

$("#oulist li").filter(function(foo) {
  console.log(this);
  console.log("foo: " + foo); // Don't really need foo, but included.
  return this; // return <li> back to be ran with .css();
}).css("background-color", "red");
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="oulist">
  <li>Foo</li>
  <li>Bar</li>
  <li>Foo</li>
  <li>Bar</li>
  <li>Foo</li>
  <li>Bar</li>
  <li>Foo</li>
</ol>
Run Code Online (Sandbox Code Playgroud)