【问题标题】:Why isn't an if condition working with .html() ? (JQuery) [closed]为什么 if 条件不能与 .html() 一起使用? (jQuery)[关闭]
【发布时间】:2022-01-21 03:57:15
【问题描述】:

我想基于 .html() 方法执行一个 jQuery 条件。 当我手动将“A”分配给 slot1 变量时,我的条件有效。 但是,当我通过 .html() 方法将 #set1 元素中的“A”分配给 slot1 变量时,“A”被正确分配并显示在 console.log 中,因为 slot1 返回“A”,但我的情况没有不起作用(#result 一直停留在“否”)。

知道如何使用 .html() 方法获得条件吗?

    // EXECUTING FUSION
$("#fusion").click(function(){
    slot1 = $("#set1").html();
    console.log(slot1);
    
    if (slot1 == "A") {
        $("#result").html("ok");
    }
    else {
        $("#result").html("no");
    }
});

【问题讨论】:

  • 使用text()html() 用于处理 html 代码
  • 您的情况有效。如果不是这样,那将是 Javascript 的一个巨大的基本错误。问题很可能是因为slot1 的值不等于A。你调试过这个吗?试试console.log(slot1) 看看值是多少。我猜这是空格导致字符串中的其他字符的问题。也许let slot1 = $("#set1").html().trim(); 会解决你的问题。
  • 你确定它是"A" 而不是" A "(带有空格)吗?也许试试slot1.trim() == "A"
  • @RoryMcCrossan 确实解决了问题,谢谢!

标签: javascript jquery if-statement


【解决方案1】:

下面的代码有效。你的也可以,但在某些情况下会失败。我相信您遇到的问题是由于空白问题以及您如何获得“slot1”输入。如果您从 a contenteditable div 中获取 .html() ,就像我在下面的代码中显示的那样,那么您需要像我在下面所做的那样删除空格,因为只需执行 .trim()将不起作用,因为空格被编码为 &nbsp 。如果这对您有帮助,我们将不胜感激

                    $("#fusion").click(function(){
                        let slot1 = $("#set1").html();
                        console.log(slot1);
                        slot1 = slot1.replace(/ /g, '');
                        console.log(slot1);
                        
                        if (slot1.trim() === "A") {
                            $("#result").html("ok");
                            console.log("ok");
                        }
                        else {
                            $("#result").html("no");
                            console.log("no");
                        }
                    });  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

                <div id="set1" contenteditable="true">This is where you type input.</div>
                <p id="result">Result</p>
                <button type="button" id="fusion" class="btn btn-primary buttonSignup" >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
            

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多