jQuery自制标签插件问题



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

这是插件的代码:

(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);

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

(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

最新更新