简体   繁体   English

JQuery 插件对每个元素的单独作用域

[英]JQuery Plugin's Separate Scope for Each Element

I am developing a carousel jquery plugin.我正在开发一个轮播 jquery 插件。 I am trying to call with more than one carousel div element like我正在尝试使用多个轮播 div 元素进行调用,例如

<div class="carousel-container">...</div>
<div class="carousel-container2">...</div>
...

Where I am calling plugin我在哪里调用插件

$(".carousel-container").mycarousel({
  // Properties
});

$(".carousel-container2").mycarousel({
  // Properties
});

Plugin Code:插件代码:

(function($) {
   $.fn.mycarousel = function(options) {
      var settings = $.extend({
        indicators : true,
        autoplay : true,
        autoplayDir : "forward",
        slidesToShow : 1,
        slidesToScroll : 1
    }, options);

    return this.each(function() {
      // JavaScript code like constructor function and its prototypes

      // variable declarations and initialization
      var outerCarouseWidth, imageWidth;
      var elements, carousel;
      ...

      // jquery code for selectors, events etc.
      var carouselInner = $(".carousel-inner");
      var carouselOuter = $(".carousel-outer");
      ...

      $(".next-link").on("click", function(e) {
            slide("next", "first");
      });
      ...
    });
   };
}(jQuery));

Well, right now I am trying to access child elements using $(this) within each function.好吧,现在我正在尝试在每个函数中使用 $(this) 访问子元素。 Like $(this).children()[0].text("abc").像 $(this).children()[0].text("abc")。

The Problem I am facing here is that, both carousel div elements are sharing the scope of variables, selectors etc. When I slide one carousel, other carousel moves as well and facing some other technical issues.我在这里面临的问题是,两个轮播 div 元素共享变量、选择器等的范围。当我滑动一个轮播时,其他轮播也会移动并面临其他一些技术问题。 How can I separate the scope of code of jquery plugin for each element with which I am calling this plugin?如何为我调用此插件的每个元素分隔 jquery 插件的代码范围?

Scope the finding of elements to the current element that the plugin is applied upon.将元素的发现范围限定为应用插件的当前元素。

Use carouselEl as the parent selector for all sub elements.使用 carouselEl 作为所有子元素的父选择器。

Like this:像这样:

``` ``

return this.each(function() {
  var carouselEl = $(this);
  ...

  // jquery code for selectors, events etc.
  var carouselInner = carouselEl.find(".carousel-inner");
  var carouselOuter = carouselEl.find(".carousel-outer");
  ...

  carouselEl.find(".next-link").on("click", function(e) {

        slide(carouselEl, "next", "first"); // This must also be scoped.. I cant see the code for this function. 
  });
  ...
});

``` ``

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM