在条件匹配后仅运行jQuery事件一次

在条件匹配后仅运行jQuery事件一次,jquery,html,Jquery,Html,我正在制作在线产品网站,我正在触发一个滚动事件,开始时只会显示12个元素,但当第8个元素滚动到顶部时,滚动事件应该只运行一次,但每次我向下滚动时它都在运行,请帮助。 这是我的密码: var navigation_offset_top = $('.prods-list li:nth-child(4)').offset().top; $(window).on("scroll",function(){ var scroll_top = $(window).scrollTop

我正在制作在线产品网站,我正在触发一个滚动事件,开始时只会显示12个元素,但当第8个元素滚动到顶部时,滚动事件应该只运行一次,但每次我向下滚动时它都在运行,请帮助。 这是我的密码:

var navigation_offset_top = $('.prods-list li:nth-child(4)').offset().top;  
    $(window).on("scroll",function(){
        var scroll_top = $(window).scrollTop(); // current vertical position from the top
        // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative
        if (scroll_top > sticky_navigation_offset_top) 
        { 
            console.log("Hi");
        }       
    });
调用以解除事件与对象的绑定

$(window).on("scroll",function(){
    var scroll_top = $(window).scrollTop(); // current vertical position from the top
    // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative
    if (scroll_top > sticky_navigation_offset_top) 
    { 
        console.log("Hi");
    }       
    $(this).unbind("scroll");
});

您可以在事件完成后解除绑定

$(此)类似。取消绑定(“滚动”);
使用
on()
off()
,并在滚动到达正确点时取消绑定事件处理程序:

var navigation_offset_top = $('.prods-list li:nth-child(4)').offset().top;  

$(window).on("scroll", doScroll);

function doScroll() {
    var scroll_top = $(window).scrollTop();
    if (scroll_top > sticky_navigation_offset_top) { 
        console.log("Hi");
        $(window).off('scroll', doScroll);
    }
};

我想你需要的是一种方法

$(window).one("scroll",function(){
    var scroll_top = $(window).scrollTop(); // current vertical position from the top
    // if scrolled more than the navigation, change its position to fixed to stick to top, otherwise change it back to relative
    if (scroll_top > sticky_navigation_offset_top) 
    { 
        console.log("Hi");
    }       
});
您可以在此处了解更多信息:

这甚至更好,因为您不需要按钮来触发fancybox。
在前面的代码中,我无法在fancybox中插入表单,因为每次我在表单中单击时,它都会重新启动fancybox。

只需删除事件处理程序。在开始时放置一个var trigger=true。在第一次单击后,将其设为false,根据它允许滚动或不允许,一些答案可以解决您的问题?如果不允许,请尝试放置y我们在中的代码。
one()
只工作一次,所以当你触摸滚动条或鼠标滚轮时,它会触发一次,而且不会再触发,因此它永远不会到达条件语句。这得到了两次向上投票?这可能是因为标题与问题不匹配。
one()
是一种只运行一次jQuery事件的正确方法,这是问题标题所要求的。您的代码运行正常,但我希望在下一个第8元素代码时运行相同的事件:
var-navigation\u-offset\u-top=$('.prods-list-li:nth-child(4)).offset().top;var-navigation\u-offset\u-top1=$('.prods-list-li:nth-child(8).offset().top$(窗口).on(“scroll”,function(){var scroll_top=$(窗口).scroll top();if(scroll_top>navigation_offset_top | | | scroll_top>navigation_offset_top1){console.log(“Hi”);$(this).解除绑定(“scroll”);}};
但它不工作..请检查一次。您有一个“)“底部有很多。回答得好。@PeterHøjlundAndersen-确实,删掉了,谢谢!
var thisHash = window.location.hash;
jQuery(document).ready(function() {

    if(window.location.hash) {
      jQuery.fancybox(thisHash, {
        padding: 20
        // more API options
      });
    }

});