【发布时间】:2016-06-29 13:37:26
【问题描述】:
每当我调用check_scroll() 函数时,我都需要将值 7 作为参数传递。
但是现在lastcount 的值不断增加,即使我调用了check_scroll() 函数。
请给我一些建议。
像我说的那样检查代码 sn-p,
首先单击first click me to initiate check_scroll function 按钮,然后在div 内滚动,您会收到一个值增加7 的警报。
然后单击按钮,然后再次滚动,但现在警报不会从 7 开始。
$("#mybutton").click(function() {
check_scroll(7);
})
function check_scroll(val) {
var lastcount = val;
$('#notification_ul').scroll(function() {
if ($('#notification_ul').scrollTop() + $('#notification_ul').innerHeight() == $('#notification_ul')[0].scrollHeight) {
$("#notification_ul").append("<br/> Some Text Append <br/>");
alert(lastcount);
lastcount = lastcount + 7;
}
})
}
div {
width: 200px;
height: 200px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notification_ul">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
<button id="mybutton">
first click me to initiate check_scroll function
</button>
【问题讨论】:
-
每次调用
check_scroll()时,您都在建立一个新 滚动处理程序——之前安装的处理程序将继续被调用。单击按钮 5 次后,将调用 5 个滚动事件处理程序。每一个都会在 7 点以lastcount开始,但每个滚动事件都会增加计数器。 -
抱歉,如何解决。每当我单击按钮时,我都需要从 7 开始递增。
-
在全局外部函数中声明
lastcount = 7。不要在 check_scroll 中传递它并像你现在所做的那样在函数中不断增加。 -
也用
console.log()代替alert();浏览器会非常积极地触发“滚动”事件,您将处理数千个警报框。 -
正如@Pointy 指出的那样。只需在绑定之前取消绑定滚动事件,就像
$('#notification_ul').off("scroll").on("scroll", function() {
标签: javascript jquery