javascript - 可重用函数中的“this”绑定(bind)?

标签 javascript jquery html scope this

我已经将一个小脚本放在一起作为一个更大的测验项目的一部分,并且正在努力理解为什么在调用函数之前在函数中设置 this 关键字。这是我的代码:

$(document).ready(function ($) {

     function nextCard() {
         console.log('yes');
         $(this).closest('.card').hide();
         $(this).parent().next().show();
     }

    $("#start").on('click', function (e) {
        e.preventDefault();

        //First card to appear
        nextCard();
    });

    $("#next").on('click', function (e) {
        e.preventDefault();
        nextCard();
    });
});

例如,为什么不将“this”设置为元素#start?

最佳答案

nextCard() 中,this 将引用 window,因为这是默认范围。因此,您的 DOM 遍历方法很可能没有像您期望的那样工作。

假设您希望函数中的 this 引用单击的 #start#next 元素,您可以提供 nextCard() 的引用 到事件处理程序方法,如下所示:

$(function($) {
  function nextCard(e) {
    e.preventDefault();
    console.log('yes');
    $(this).closest('.card').hide();
    $(this).parent().next().show();
  }

  $("#start, #next").on('click', nextCard);
});

关于javascript - 可重用函数中的“this”绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45218962/

相关文章:

javascript - HTML5 文件系统 : file not created on device

javascript - 在函数内调用函数有好处吗?

javascript - Jquery 表单提交返回 false 不起作用

javascript - jQuery 中的不透明度

javascript - ASP.NET MVC - 更改选项卡 AJAX RenderAction

html - 在一个 div 中制作背景图像 B/W

html - 在元素中居中放置多个链接

javascript - 向国际用户显示消息

javascript - JS/jQuery - 如何从元素 ID 中获取数字并将其用作函数中的变量?

javascript - Jquery 无法调用未定义的方法替换