我正在尝试使用相同的JavaScript在同一页面上创建图像滑块和文本滑块。但有些如何不能按预期正常工作。我研究了一些关于这一点,但我发现的唯一的事情是使用无冲突,但它也不起作用。当我排除第一个JavaScript代码时,数字2滑块正常工作,但当我包含数字1滑块时,数字2不能正常工作。有没有办法可以避免相互冲突?如果是的话那怎么办?这是我的JavaScript代码:
<script> //number-2
sliderInt = 1;
sliderNext = 2;
$(document).ready(function() {
$('#slider > img#1').fadeIn(150);
startSlider();
})
function startSlider() {
count = $('#slider > img').size();
loop = setInterval(function() {
if(sliderNext > count) {
sliderInt = 1;
sliderNext = 1;
}
$('#slider > img').fadeOut(150);
$('#slider > img#' + sliderNext).fadeIn(150);
sliderInt = sliderNext;
sliderNext = sliderNext + 1;
}, 3000);
}
function prev() {
newSlide = sliderInt - 1;
showSlide(newSlide);
}
function next() {
newSlide = sliderInt + 1;
showSlide(newSlide);
}
function stopLoop() {
window.clearInterval(loop);
}
function showSlide(id) {
stopLoop();
if(id > count) {
id = 1;
}else if(id < 1) {
id = count;
}
$('#slider > img').fadeOut(150);
$('#slider > img#' + id).fadeIn(150);
sliderInt = id;
sliderNext = id + 1;
startSlider();
}
$('#slider > img').hover(
function() {
stopLoop();
},
function() {
startSlider();
}
// In the End of the line don't put comma ','
);
</script>
<script> //number-1
textsliderInt = 1;
textsliderNext = 2;
$(document).ready(function() {
$('#slider_text > p#1').fadeIn(300)
textsliderStart();
})
function textsliderStart() {
count = $('#slider_text > p').size();
loop = setInterval(function() {
if(textsliderNext > count) {
textsliderInt = 1;
textsliderNext = 1;
}
$('#slider_text > p').fadeOut(300);
$('#slider_text > p#' + textsliderNext).fadeIn(300);
textsliderInt = textsliderNext;
textsliderNext = textsliderNext + 1;
}, 3000)
}
</script>
答案 0 :(得分:3)
将var
放在count = $('#slider_text > p').size();
和loop = setInterval(function() {
当你不使用var时,你在全局范围内声明count和loop