首页 > 解决方案 > 在 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>

我究竟做错了什么?

标签: javascriptjqueryplugins

解决方案


您想将选择器传递给您的插件,should然后对其进行评估(在您的插件的上下文中)。

问题是 jQuery首先评估您的选择器,然后将结果传递给您的插件,这样您就可以得到任何结果(在您的情况下,只有 1 个元素,因为您使用了eq(1))。您的$(this)工作正如预期的那样,只是输入插件的数据已经被过滤。

我还查看了您提供的文章,但在那里他们只传递了一组元素(通过选择器),然后在该上下文中执行某些操作,在我看来您也应该这样做。


推荐阅读