如何在html上添加javascript函数

How to add javascript function on html?

本文关键字:添加 javascript 函数 html      更新时间:2023-09-26

我不知道我的代码出了什么问题。我无法在javascript中传递函数,[我不想将其内联]

我的问题是我的上一个按钮和下一个按钮不起作用,我也试图在上一个和下一个中设置return false以停止刷新页面,但它仍然在点击时刷新。

这是我的代码[请参阅我的评论]和我的代码笔:

  $(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('prev').onclick时,您得到了一个数组。像下面的一样使用它

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

getElementsByClassName返回一个HTMLCollection。因此,您需要传递要添加onclick函数的相关索引

document.getElementsByClassName('next')[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))
}

由于您已经在使用jquery,如果您使用类选择器,您可以避免所有这些

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