我不知道我的代碼有什麼問題。我不能通過我的JavaScript函數,[我不想把它內聯]如何在html上添加javascript函數?
我的問題是我的上一頁按鈕和下一個按鈕不起作用,我也試圖把prev和next停止刷新頁面,但它仍然點擊刷新。
這是我的代碼[另請參見我的評論]我codepen:
$(document).ready(function slider() {
$('#img1').show('fade', 500);
$('#img1').delay(5000).hide("slide", { direction: 'left' }, 500);
});
var count = 2;
setInterval(function loop() {
var all = document.getElementsByTagName('li').length; // <-- i got the li elements so i did the same to prev and next
$('#img' + count).show('slide', { direction: 'right' }, 500);
$('#img' + count).delay(5500).hide('slide', { direction: 'left' }, 500);
if (count === all) {
count = 1;
} else {
count += 1;
}
}, 6500);
var sliderInt = 1;
var sliderNext = 2;
document.getElementsByClassName('prev').onclick = function prev() { // <-- not working
console.log('clicked prev');
var newSlide = sliderInt - 1;
showSlide(newSlide);
return false;
}
document.getElementsByClassName('next').onclick = function next() { // <-- not working
console.log('clicked next');
var newSlide = sliderInt + 1;
showSlide(newSlide);
return false;
}
function stopLoop() {
window.clearInterval(loop());
}
function showSlide(id) { // <-- this function doesn't work from prev and next
stopLoop(); // <-- I want to stop the loop() function when prev and next is clicked
if (id > count) {
id = 1;
} else if (id < 1) {
id = count;
}
$('li').hide('slide', { direction: 'left' }, 500);
$('#img' + id).show('slide', { direction: 'right' }, 500);
sliderInt = id;
sliderNext = id + 1;
window.slider(); // <-- I want to call the function slider here
}
修復演示將非常感激:)
是
,'document.getElementsByClassName()'返回一個數組不是一個DOM對象,所以你不能直接對響應做一個'.onlick'。另外,一旦你做了'onclick',你不需要命名該函數,它可以採用一個匿名函數,例如'.onclick = function(){// do stuff} – Stu