我是 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/