我是 jQuery 新手,刚刚学习新东西。我刚刚阅读 Chris Coyer 的文章,发现了以下代码:
$.fn.faq = function(options) {
return this.each(function(i, el) {
var base = el,
$base = $(el);
console.log(options);
base.init = function() {
// Do initialization stuff
$base
.find("dd")
.hide()
.end()
.find("dt")
.click(function() {
var ans = $(this).next();
if (ans.is(":visible")) {
base.closeQ(ans);
} else {
base.openQ(ans);
}
})
};
base.openQ = function(ans) {
// Open panel
ans.show();
// Do callback
options.qOpen.call();
};
base.closeQ = function(ans) {
// Open panel
ans.hide();
// Do callback
options.qClose.call();
};
base.init();
});
};
$("dl").faq({
qOpen: myQuestionOpenCallback,
qClose: myQuestionCloseCallback
});
function myQuestionOpenCallback() {
alert("answer opened!");
}
function myQuestionCloseCallback() {
alert("answer closed!");
}
现在我不太明白这部分代码:
return this.each(function(i, el) {
代码中的第二行,i
和el
到底是什么?我没有看到这些参数被传递到每个函数中。
我询问了一位资深同事,得到了以下答案:
Many plugins start that way. Since most plugins are chainable, they have to return this. And they also have to loop through the elements from the selector,
return this.each(function(i, el) {
does them both. A loop, then the return.
但是我还是不太明白。
JS Fiddle 可以找到 here .
最佳答案
在 jQuery 插件内,this
指的是代表您调用插件的 jQuery 对象。例如,对于这个 faq
插件,如果我调用 $('#someDiv').faq({ ... });
,this
将与插件函数内的 $('#someDiv')
相同。
因为它是一个代表 DOM 节点选择的 jQuery 对象,所以您可以在其上调用 jQuery 方法 .each()
,该方法采用一个函数,该函数在调用时会获得给定的两个参数对于选择中的每个 DOM 节点:
- 索引(0、1、2 等)
- DOM 节点本身
.each()
还会返回调用它的对象,因此您最终会从插件返回 $('#someDiv')
对象。这太棒了,因为之后我们可以直接调用其他 jQuery 方法(“链接”)。例如$('#someDiv').faq({ ... }).hide();
立即隐藏它。
关于javascript - 了解插件代码中 $.each 内部传递的参数的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29182320/