If和else部分在查询中不工作

if and else part not working in query

本文关键字:查询 工作 else If      更新时间:2023-09-26

我尝试了jquery中的if else语句,但它不起作用。这是我的代码。

jQuery(document).ready(function () {
        jQuery(".checkboxes").hide();
        //toggle the componenet with class msg_body
        jQuery(".Select").click(function () {
            jQuery(this).next(".checkboxes").slideToggle(500);
            if ($(".select").text() == "+") {
                alert('hi');
                $(".select").html() == "-"
            }
            else {
                $(".select").text() == "+";
            }
            return false;
        });
    });

我猜是打错了。用大写的"S"代替点击事件中的"S"

尝试下面的代码:-

if ($(".Select").text() == "+") {
                alert('hi');
                $(".Select").html("-");
            }
            else {
                $(".Select").text() == "+";
            }

或者直接使用$(this)如下所示:-

 if ($(this).text().trim() == "+") {
            $(this).html("-");
        } else {
            $(this).text("+");
        }

不能给函数调用赋值。您的代码应该抛出类似Uncaught ReferenceError: Invalid left-hand side in assignment

的错误。
jQuery(function ($) {
    $(".checkboxes").hide();
    //toggle the componenet with class msg_body
    $(".Select").click(function () {
        $(this).next(".checkboxes").slideToggle(500);
        $(this).text(function (i, txt) {
            return txt.trim() == '+' ? '-' : '+'
        })
        return false;
    });
});

首先,您使用两个不同的类.Select.select。我认为问题就在这里。第二件事,它应该是html('-')而不是html() == '-',因为它是一个逻辑/条件语句,它将返回一个布尔值。它不是一个赋值语句。所以你的代码应该是:

jQuery(document).ready(function () {
    jQuery(".checkboxes").hide();
    //toggle the componenet with class msg_body
    jQuery(".select").click(function () {
        jQuery(this).next(".checkboxes").slideToggle(500);
        if ($(".select").text() == "+") {
            alert('hi');
            $(".select").html("-");
        }
        else {
            $(".select").text("+");
        }
        return false;
    });
});

我认为正确的类是select,因为你使用它比Select更多。

查看这个小提琴:JsFiddle你应该把你的代码改成这个,同时把它赋值为$(".Select").html("-");

jQuery(document).ready(function () {
        jQuery(".checkboxes").hide();
        //toggle the componenet with class msg_body
        jQuery(".Select").click(function () {
            jQuery(this).next(".checkboxes").slideToggle(500);
            if ($(".Select").text() == "+") {
                alert('hi');
                $(".Select").html("-");
            }
            else {
                $(".Select").text("+");
            }
            return false;
        });
    });