javascript - 为什么我需要使用函数作为参数而不能只使用它返回的值

标签 javascript jquery

我是 jQuery 的新手,正在浏览涵盖 DOM 更改的教程。

这是该教程中的示例。

HTML 部分:

<h1>My Awesome Post</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod</p>

脚本

(function() {
  $('p').eq(0).after(function() {
    return $(this).prev();
  });
})();

我不明白为什么我需要在这里使用这个函数,如果它所做的只是返回一个值?为什么下面的语句不起作用?

$('p').eq(0).after( $(this).prev());

最佳答案

一切都与范围和this的值(value)有关

在第一个示例中,函数创建了一个新范围,就像所有函数一样,其中 this 是当前迭代的元素,因为 jQuery 在内部迭代元素集合并设置 的值>这个相应地

$('p').eq(0).after(function() { // new scope, where "this" is the element
    return $(this).prev();
});

在第二个代码中,没有设置特殊的范围,所以范围是代码所在的任何范围,很可能是窗口范围,或者如果它在 $(document).ready 中范围,this 将是文档

$('p').eq(0).after( $(this).prev()); // there is no scope here

您可以阅读更多关于 functions and function scope on MDN 的信息

关于javascript - 为什么我需要使用函数作为参数而不能只使用它返回的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20587356/

相关文章:

javascript - 使用jquery读取json中的对象

javascript - 使用javascript在iPad safari上打开一个新标签

jquery - 如何从 Greasemonkey 页面事件中获取 jQuery ajax 调用

javascript - jQuery .change() 函数因数字输入而严重延迟

javascript - 如何使用样式正则表达式剥离 p 标签

internet-explorer - 让 Google Chrome 忽略 IE Javascript

jquery - 计算具有变化值的多个 div

jquery 数组 .val()

javascript - 为什么 firebug 控制台中的 POST 没有显示任何内容,并且以下 jQuery 代码中的文件没有上传?

javascript - 将图像填充到 Canvas 中