jQuery 事件中的自调用函数不起作用

Self invoking function inside jQuery event is not working

jQuery 事件中定义的自调用函数不起作用,但为什么?

$('div').on('click', function(){
  $('div').text($('div').text() + 1)
  (function(){
    $('div').text($('div').text() + 0)
  })();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>text</div>

编辑: 下面的答案集中在 this 关键字上,所以我将 this 参数更改为 'div'。还是不行。

IIFE 中,this 指的是另一个上下文。每个函数都有自己的上下文。您可以使用 arrow function, explicitly binding of the context 或仅将 this 引用保留到另一个变量中并使用它。 还有一点,您错过了在第一个语句之后放置 ;,这会导致错误。

也不要在该代码中使用这种样式 $('div'),这会找到所有 div,但会得到第一个的文本,所以你做的工作比它需要的多。

箭头函数

$('div').on('click', function() {
    $(this).text($(this).text() + 1);
    (() => {
      $(this).text($(this).text() + 0)
    })();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>text</div>

上下文的显式绑定

$('div').on('click', function(){
    $(this).text($(this).text() + 1);
    (function() {
        $(this).text($(this).text() + 0)
    }).bind(this)();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>text</div>

将引用保存到另一个变量中

$('div').on('click', function(){
    const that = this;
    $(that).text($(that).text() + 1);
    (function(){
       $(that).text($(that).text() + 0)
    })();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>text</div>

$(document).ready(function(){
$('div').on('click', function(){
 $(this).text($(this).text() + 1);
    var divelement = $(this);
 (function(element){
   element.text($(element).text() + 0);
  })(divelement);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>text</div>

你的问题是你在 $('div').text($('div').text() + 1)

的末尾漏掉了一个 ;

没有 ; 就像你写的一样:

$('div').text($('div').text() + 1)(function(){
   $('div').text($('div').text() + 0)
})();

但是因为text($('div').text() + 1)没有return一个函数,你会得到这个错误。

Uncaught TypeError: $(...).text(...) is not a function

在这种情况下,您必须使用 ; 来结束语句。

ecma-262: 11.9.2 Examples of Automatic Semicolon Insertion

The source

a = b + c
(d + e).print()

is not transformed by automatic semicolon insertion, because the parenthesised expression that begins the second line can be interpreted as an argument list for a function call:

a = b + c(d + e).print()

所以你必须写:

$('div').text($('div').text() + 1);
(function(){
   $('div').text($('div').text() + 0)
})();