为了让我的问题更具体,我阅读了 .each() for jQuery 的文档,但我有点困惑。我有这段代码:
$.fn.imgAreaSelect = function (options) {
options = options || {};
this.each(function () {
if ($(this).data('imgAreaSelect')) {
if (options.remove) {
$(this).data('imgAreaSelect').remove();
$(this).removeData('imgAreaSelect');
}
else
$(this).data('imgAreaSelect').setOptions(options);
}
else if (!options.remove) {
if (options.enable === undefined && options.disable === undefined)
options.enable = true;
$(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
}
});
if (options.instance)
return $(this).data('imgAreaSelect');
return this;
};
现在我不明白的是,为什么每个函数都没有索引或元素?这段代码来 self 试图阅读的一个 jQuery 插件。我也不太明白$.fn。在顶部,我知道它代表原型(prototype),但这里究竟发生了什么?
最佳答案
each 函数可以接受一个接受索引的函数作为参数,但它是可选的。
为了简单起见,.each
被实现为让 this
引用当前元素。
但是,.each
可以接受索引作为其回调的参数。
在 jQuery API 中有一个使用示例
$('li').each(function(index) {
alert(index + ': ' + $(this).text());
});
引用资料 - http://api.jquery.com/each/
关于javascript - 在 jQuery 中,this.each() 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3106414/