简体   繁体   English

无法访问jQuery事件处理程序中的全局变量

[英]Can not access global variables inside a jQuery event handler

I am using the following code to track the scrolling and I want to put the selected element variables outside the event handler so they are not called each time the user scrolls thereby saving resources. 我正在使用以下代码来跟踪滚动,并且我想将所选元素变量放在事件处理程序之外,以便每次用户滚动时都不会调用它们,从而节省了资源。 The following only works if I put the first two variables inside the event handler: 仅当我将前两个变量放入事件处理程序中时,以下内容才有效:

    var recommend_con_list=$(".recommend_con_list")
    var recommend_con=$('.recommend_con')
    $(window).scroll(function () {

        var y=$(window).scrollTop()
        if(y > 82){
            recommend_con.css({position:"fixed",top:"0"})
        }else{
            recommend_con.css({position:"",top:""})
        }
    });

If you want to optimize further, I would use this: 如果您想进一步优化,可以使用以下方法:

$(document).ready(function () {
    var recommend_con_list = $(".recommend_con_list").get(),
        recommend_con = $('.recommend_con').get(),
        $window = $(window);

    $window.scroll(function () {
        var y = $window.scrollTop();
        if (y > 82) {
            for (var i = 0, j = recommend_con.length; i < j; i++) {
                recommend_con[i].classList.add("special");
            }
        } else {
            for (var i = 0, j = recommend_con.length; i < j; i++) {
                recommend_con[i].classList.remove("special");
            }
        }
    });
});

With this CSS: 使用此CSS:

<style type="text/css">
    .special {
        position: fixed;
        top: 0;
    }
</style>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript jquery访问事件监听器'this'内的全局变量未被使用 - Javascript jquery access global variables inside an event listner 'this' is not used 无法访问事件处理程序方法中的全局变量(javascript) - can't access to a global variable in event handler method (javascript) 如何允许JQuery事件处理程序访问模块模式中的变量 - How to allow JQuery event handler to access variables in module pattern 如何访问在事件监听器中设置的全局变量? - How do I access global variables that are set inside an event listener? 无法使用事件处理程序访问对象内的对象 - Can't access object inside object using an event handler jQuery事件回调和全局变量 - jQuery event callback and global variables 如何从本地组件的事件处理程序内部访问全局组件和本地组件? - How to access the global component and local component from inside an event handler of the local component? 在另一个事件侦听器函数内定义的事件侦听器函数是否访问全局变量的副本? - Does an event listener function defined inside another event listener function access the copy of global variables? 在事件处理程序中修改外部变量 - Modifying outside variables inside an event handler 获取对jQuery事件处理程序中动态绑定事件的context元素的访问 - Get access to the context element of a dynamically bound event inside the event handler in jQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM