我已经将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);
。这里发生了什么,我该如何解决?
答案 0 :(得分:0)
您需要在事件之外定义函数,并将变量作为参数传递给scrollToLi
函数,如:
function scrollToLi( liNum ) {
console.log("liNum is: " + liNum);
$('ul#matchesDropdown').animate({
scrollTop: $('ul#matchesDropdown li:nth-child(' + liNum + ')').position().top
}, 'fast');
}