我试着做一个小的标签插件,并使用一些学习网站的代码,我不记得了。问题:当我在一个页面上初始化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);发布于 2019-12-13 18:07:08
您的问题是,您使用的变量没有声明。这是全局定义变量,导致两个选项卡部件共享状态。修正:
(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://stackoverflow.com/questions/59327523
复制相似问题