好的,所以我在 jQuery 中创建了一个名为的函数,$.fn.customTabs
并将其中的变量设置为 DOM 中的某些元素。当我第二次调用它时,变量被设置为不同的 DOM 元素并影响我对函数的第一次调用。
知道如何在每个函数调用中使用某些实例变量吗?
编辑
$.fn.customTabs = function(data,user_options) {
$this = $(this);
alert($this.attr('id'));
var options =
{
speed : 750,
startIndex : 0,
duration : 10000,
height : "300px"
},
final_options = {
"width" : "100% - 5px",
"position" : "relative",
"margin" : "0",
"padding" : "5px"
};
$.extend(options,user_options);
var tabPadding = parseInt(final_options.padding,10);
var cssTabHeight = parseInt(options.height,10) - tabPadding + "px";
$this.css(final_options);
var num = data.length - 1;
if(data) {
$container = $('<ul class=\"tabsContainer\">').css({
height : options.height,
position : "relative",
"list-style" : "none",
padding : "0",
margin : "0"
});
for(var count = 0; count <= num; count++) {
$object = data[count];
$tab = $('<li id=\"tab_' + count + '\" class=\"tab\">').css({
height : cssTabHeight
});
if($object.element) {
$object.element.css({
margin : "0",
padding : $object.element.css('padding') || "0"
});
if($object.element.is('a')) {
$tab.css({
"text-align" : "center"
});
$object.element.find('img').css({
"max-height" : "100%",
"max-width" : "100%"
});
} else if($object.element.is('img')) {
$tab.css({
"text-align" : "center"
});
$object.element.css({
"max-height" : "100%",
"max-width" : "100%"
});
} else {
$object.element.css({
width : "100% - " + tabPadding,
height : "100%"
});
}
$object.element.appendTo($tab);
} else {
}
$container.append($tab);
}
$tabWrapper = $('<div>').html($container).css({
overflow: "hidden"
});
$this.html($tabWrapper);
} else {
}
var tabIndex = options.startIndex,
x,
tabHeight = parseInt(cssTabHeight,10) + tabPadding;
var interval = setInterval(function() {
makeInterval();
},options.duration);
$('.tabMenuButton').click(function() {
clearInterval(interval);
var element = this;
var index;
$('.tabMenuButton').each(function(i, ele) {
if(ele == element) {
index = i;
}
});
var diffrence = index - tabIndex;
if(diffrence < 0) {
x = "-=" + (tabHeight*parseInt(diffrence,10));
changeTab(x);
} else if(diffrence > 0) {
x = "-=" + (tabHeight*diffrence);
changeTab(x);
}
tabIndex = index;
interval = setInterval(function() {
makeInterval();
},options.duration);
});
var makeInterval = function() {
if(tabIndex != num) {
tabIndex++;
x = "-=" + tabHeight;
} else {
tabIndex = 0;
x = "+=" + (tabHeight*num);
}
changeTab(x);
}
var changeTab = function(distance) {
$container.animate({
"top" : distance + "px"
}, options.speed);
}
return $this;
}
在第二次调用此函数后,将$container
设置为在第二次调用中为两个间隔创建的元素。
顺便说一句,当同一页面上有两个代码时,这段代码的工作就会变得混乱。