javascript - 在 jquery 插件中使用链式选择器和方法作为选项,对此感到困惑,$(this) 范围
问题描述
我试图设置一个 jQuery 插件,它有一个选项是一个使用选择器和方法的 jquery 对象find
这是使用https://learn.jquery.com/plugins/basic-plugin-creation/上的“greenify”教程的精简示例
(function ( $ ) {
$.fn.greenify = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
backgroundColor: "white"
}, options );
// Greenify the collection based on the settings variable.
return this.each(function(){
$(this).find(settings.target).css({
backgroundColor: settings.backgroundColor
});
});
};
}( jQuery ));
$(".target").greenify({
target: $(".something").eq(1).find(".another"),
backgroundColor: "red"
});
.target * {
padding: 10px;
margin: 10px;
background: blue;
border: 4px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target">
target
<div class="something">
something
<div class="another">another</div>
</div>
<div class="something">
something
<div class="another">another</div>
</div>
<div class="something">
something
<div class="another">another</div>
</div>
</div>
<div class="target">
target
<div class="something">
something
<div class="another">another</div>
</div>
<div class="something">
something
<div class="another">another</div>
</div>
<div class="something">
something
<div class="another">another</div>
</div>
</div>
<div class="target">
target
<div class="something">
something
<div class="another">another</div>
</div>
<div class="something">
something
<div class="another">another</div>
</div>
<div class="something">
something
<div class="another">another</div>
</div>
</div>
我究竟做错了什么?
解决方案
您想将选择器传递给您的插件,should
然后对其进行评估(在您的插件的上下文中)。
问题是 jQuery首先评估您的选择器,然后将结果传递给您的插件,这样您就可以得到任何结果(在您的情况下,只有 1 个元素,因为您使用了eq(1)
)。您的$(this)
工作正如预期的那样,只是输入插件的数据已经被过滤。
我还查看了您提供的文章,但在那里他们只传递了一组元素(通过选择器),然后在该上下文中执行某些操作,在我看来您也应该这样做。
推荐阅读
- lua - 我在使用 haproxy 中使用 lua 根据查询参数选择后端时遇到问题
- sql - ORACLE SQL - 行名上的通配符
- xcode - 小型集合视图单元格
- r - 我如何在另一个选举半圆中将几年与 plotly 或 ggplot 进行比较?
- flutter - Override gives me an error I cant find the function
- wordpress - 即使在使用更好的搜索和替换插件后,我在解决 Wordpress 中的混合内容时仍面临错误?{WordPress}
- html - 角度模板解析错误,无法绑定属性
- sql - 理解: floor((row_number() over (ORDER BY CHDR.UNIQUE_NUMBER ASC)-1)/100)
- string - Ada 中的多行字符串文字
- python - Pandas 如何使用 dt 按月和年分组