如果=true,则停止jQuery函数

Stopping a jQuery function if = true

本文关键字:jQuery 函数 true 如果      更新时间:2023-09-26

我正在为我的新品牌创建一个网站,作为我第一次深入接触jQuery,我发现了一些与div状态有关的问题。代码中的if语句检查#homebutton的文本是否等于'blog'或'home',然后为每个按钮发出不同的scrollTop()命令。问题是我需要停止jQuery函数——比如说,如果博客是文本,我不希望它运行该函数(包括将#homebutton的文本更改为home),然后运行if-text=home-if语句(因为文本已经更改)。我需要一种方法,在jQuery函数执行其中一个scrollTop()命令后停止它,或者我希望有人向我展示如何编写一个可以消除这个问题的IF语句。

        $(document).ready(function(){ 
        });
        $("#askbutton").click(function() { 
            $("html, body").animate({ scrollTop: 0 }, "fast");
            $("#askpage").toggle("slow");
            $("#tumblrcontent").toggle("slow");
            $("#homebutton").text("HOME");
          });

        $(window).scroll(function() {
            var targetDiv = $('#homebutton');
            var matchHeight = $('#tumblrcontent').position().top;
            if($(document.body).scrollTop() >= matchHeight) {
                // this is where you're css amendments would be done
                if (targetDiv.text('BLOG')) {  targetDiv.text('HOME'); }
            } else {
                if (targetDiv.text('HOME')) { targetDiv.text('BLOG'); }
            }
        });
        $("#homebutton").click(function() { 
        if ($(this).text("HOME") && $("#tumblrcontent").css('display', 'none')){
                $("#askpage").fadeOut("slow");
                $("#tumblrcontent").fadeIn("slow");
                $("html, body").animate({ scrollTop: 0 }, "slow"); 
                $(this).text("BLOG");
                //if tumblrcontent is not shown and text says home, this means that #askpage will be showing.
        }
        if ($(this).text("HOME") && $("#askpage").css('display', 'none')){
                $("html, body").animate({ scrollTop: 0 }, "slow"); 
        }
        if ($(this).text("BLOG") && $("#askpage").css('display', 'none'))  {
            $(this).text("HOME");
            $('html,body').animate({scrollTop:$("#tumblrcontent").offset().top}, "slow");
        }
        });
    $("#homebutton").click(function() { 
                    if ($(this).text =="HOME" && $("#tumblrcontent").is('display', 'none')){
                    }
}

检查此处

我很难弄清楚你想做什么。让我们检查一下你的代码,我会告诉你你的代码是做什么的。。。

        if($(document.body).scrollTop() >= matchHeight) {

上面的语句说:"如果文档主体的scrollTop位置大于或等于匹配高度变量,则执行下一组括号内的操作,直到其他块。"

            // this is where you're css amendments would be done
            if (targetDiv.text('BLOG')) {  targetDiv.text('HOME'); }

这一行说:"将targetDiv的文本值设置为字符串'BLOG',然后计算文本函数的返回值。如果这是真的,那么将targetDiv的文本属性设置为字符串'HOME'。"

我非常怀疑你的意思,因为那毫无意义。这可能就是你的问题所在。几行之后,我看到了相同的问题:

            if (targetDiv.text('HOME')) { targetDiv.text('BLOG'); }

您正在设置目标div的文本值的值。您不是在评估它。要评估值,请改为:

            if (targetDiv.text() === 'HOME') { targetDiv.text('BLOG'); }

该行显示"如果targetDiv的文本值为"HOME",则将targetDiv文本值设置为"BLOG"。"

这就是你想要做的吗?