2016-07-24 86 views
1

我不知道我的代碼有什麼問題。我不能通過我的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 
    } 

修復演示將非常感激:)

+0

var list = document.getElementsByClassName('next or prev'); for (var i = 0, len = list.length; i < len; i++) { (function(i){ // creating closure list[i].addEventListener('click',function(){ // code you want to execute on click of next or prev } }(i)) } 

,'document.getElementsByClassName()'返回一個數組不是一個DOM對象,所以你不能直接對響應做一個'.onlick'。另外,一旦你做了'onclick',你不需要命名該函數,它可以採用一個匿名函數,例如'.onclick = function(){// do stuff} – Stu

回答

0

當您使用document.getElementsByClassName('prev').onclick你有一個陣列。像下面這樣使用它

document.getElementsByClassName('prev')[0].onclick 
document.getElementsByClassName('next')[0].onclick 
0

getElementsByClassName返回一個HTMLCollection。所以,你需要通過相關指標要添加的onclick功能

document.getElementsByClassName('next')[0] 

但是,這將附加事件僅在集合中的第一個元素。

的更相關的例子如您已經使用jquery你能避免這一切如果首先使用類選擇

$('.next or .prev').on('click',function(event){ 
    // relevant code 
}) 
相關問題