首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery自制的选项卡插件问题

jQuery自制的选项卡插件问题
EN

Stack Overflow用户
提问于 2019-12-13 17:48:35
回答 1查看 30关注 0票数 0

我试着做一个小的标签插件,并使用一些学习网站的代码,我不记得了。问题:当我在一个页面上初始化2次插件时,它在两个地方同时工作。这是一支带完整箱子的钢笔:https://codepen.io/leshiq/pen/XWJjmxy

下面是插件的代码:

代码语言:javascript
复制
(function($){       
  jQuery.fn.lightTabs = function(options){

    var createTabs = function(){
      tabs = this;
      i = 0;
      if ($(tabs).children().first().children().length < 2) {
        tabs_list = $(tabs).children().first().children().children();
      } else {
        tabs_list = $(tabs).children().first().children();
      }
      console.log(tabs_list);
      showPage = function(i){
        $(tabs).children().last().children().hide();
        $(tabs).children().last().children().eq(i).show();
        tabs_list.removeClass("active");
        tabs_list.eq(i).addClass("active");
      }

      showPage(0);
      console.log($(tabs).children().last().children());

      tabs_list.each(function(index, element){
        $(element).attr("data-page", i);
        i++;                        
      });

      tabs_list.click(function(){
        showPage(parseInt($(this).attr("data-page")));
      });       
    };    
    return this.each(createTabs);
  };  
})(jQuery);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-13 18:07:08

您的问题是,您使用的变量没有声明。这是全局定义变量,导致两个选项卡部件共享状态。修正:

代码语言:javascript
复制
(function($){       
  jQuery.fn.lightTabs = function(options){

    function createTabs() {
      const tabs = this;
      const tabs_list = ($(tabs).children().first().children().length < 2)
        ? $(tabs).children().first().children().children()
        : $(tabs).children().first().children();
      console.log(tabs_list);
      function showPage(i) {
        $(tabs).children().last().children().hide();
        $(tabs).children().last().children().eq(i).show();
        tabs_list.removeClass("active");
        tabs_list.eq(i).addClass("active");
      }

      showPage(0);
      console.log($(tabs).children().last().children());

      tabs_list.each(function(index, element){
        $(element).attr("data-page", index);
      });

      tabs_list.click(function(){
        showPage(parseInt($(this).attr("data-page")));
      });       
    }

    return this.each(createTabs);
  };  
})(jQuery);

工作代码:https://codepen.io/apoco/pen/gObwPwR

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59327523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档