简体   繁体   中英

Why does the value of a boolean change after stepping out of a function?

After I click on a li-element where the class-attribute contains "disabled selected", disabled gets the value "true" but after stepping out the function the last if-statement is called.

    var disabled = false;
    $("li").click(function () {
        if ($(this).attr("class") == "disabled selected") {
            disabled = true;
        }
    });
    if (disabled) {
        alert("disabled is true");
    }
    if (!disabled) {
        alert("disabled is false");
    }

You should move both the if statements inside the click handler.

var disabled = false;
$("li").click(function () {
    if ($(this).attr("class") == "disabled selected") {
        disabled = true;
    }
    if (disabled) {
        alert("disabled is true");
    }
    else {
        alert("disabled is false");
    }
});

最后两个if测试在click事件处理程序之前运行,因此disabled的值尚未更改。

The callback is not invoked until the 'li' is clicked. However, the proceeding two 'if' statements are executed immediately. You'll want to place them within the callback.

var disabled = false;
$("li").click(function () {
    if ($(this).attr("class") == "disabled selected") {
        disabled = true;
    }
    if (disabled) {
     alert("disabled is true");
    }
    if (!disabled) {
     alert("disabled is false");
    }
});

The function is executed when the li element is clicked. When the script is initially evaluated, the click event has not been fired.

The problem is two-fold.

First, as pointed out by several posters, you need to put those if tests inside the click handler. As it stands now, they execute outside the click handler's scope, which I suspect is not when you want them to execute.

Second, the if ($(this).attr("class") == "disabled selected") { will only get you a "truthy" value if the class string is 'disabled selected' . If the class string is 'selected disabled' (or 'otherClass disabled selected' or 'disabled selected draggable' , etc.) then you will get a false value returned as a result of the comparison.

Try:

$("li").click(function () {
    var i = $(this); //Multiple variables used for better step-line debugging.
    var hasDisabled = i.hasClass('disabled');
    var hasSelected = i.hasClass('selected');
    var disabled = false;
    if (hasDisabled && hasSelected) {
        disabled = true;
    }
    if (disabled) {
        alert("disabled is true");
    }
    if (!disabled) {
        alert("disabled is false");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM