jQuery click事件甚至不会触发点击

时间:2018-11-02 14:45:56

标签: javascript jquery function switch-statement click

我已经将click事件分配给了像这样的图标:

$('#nextMatches i').click(function(){
          dropdownClickCount += 1;
          var CC = dropdownClickCount; console.log(CC)
          var Len = matches.length;
          var liNum;

          function addPrev() {
                $('#prevMatches').addClass('prev-in-play');
            }
            function addNext() {
                $('#nextMatches').addClass('next-in-play');
            }
            function subPrev() {
                $('#prevMatches').removeClass('prev-in-play');
            }
            function subNext() {
                $('#nextMatches').removeClass('next-in-play');
            }
            function scrollFull() {
                $('ul#matchesDropdown').animate({
                    scrollTop: $('ul#matchesDropdown').prop("scrollHeight")
                    }, 'fast');
            }
            function scrollToLi() {
                console.log("liNum is: "+liNum);
                $('ul#matchesDropdown').animate({
                    scrollTop: $('ul#matchesDropdown li:nth-child('+liNum+')').position().top
                    }, 'fast');
            }

        if (Len >= 7 && Len <= 12) {
            switch (CC) {
                case 0:
                    break;
                case 1:
                    addPrev();
                    subNext();
                    scrollFull();
                    break;
                }
            }
        else if (Len >= 13 && Len <= 18) {
            switch (CC) {
                case 0:
                    break;
                case 1:
                    liNum = 7;
                    addPrev();
                    scrollToLi();
                    break;
                case 2:
                    subNext();
                    scrollFull();
                    break;
                }
            }
        else if (Len >= 19 && Len <= 24) {
            switch (CC) {
                case 0:
                    break;
                case 1:
                    liNum = 7;
                    addPrev();
                    scrollToLi();
                    break;
                case 2:
                    liNum = 13;
                    scrollToLi();
                    break;
                case 3:
                    subNext();
                    scrollFull();
                    break;
                }
            }
});

并遇到一个小问题:在if-else的{​​{1}}中,Len >= 19 && Len <= 24为true时,scrollToLi()函数实际上并不执行滚动动画。它根据case 2调用记录liNum的值,但不设置动画。但是,再次单击该图标时,它将触发console.log("liNum is: "+liNum);。这里发生了什么,我该如何解决?

1 个答案:

答案 0 :(得分:0)

您需要在事件之外定义函数,并将变量作为参数传递给scrollToLi函数,如:

function scrollToLi( liNum ) {
  console.log("liNum is: " + liNum);

  $('ul#matchesDropdown').animate({
    scrollTop: $('ul#matchesDropdown li:nth-child(' + liNum + ')').position().top
  }, 'fast');
}