Javascript布尔值true变为false,false不会变为true

Javascript boolean true turns false, false does not turn true

本文关键字:true false 变为 Javascript 布尔值      更新时间:2023-09-26

这看起来非常琐碎,但我不确定为什么它不起作用。

我的web应用程序使用div而不是复选框。我正在使用一个名为"contentEditable"的javascript功能为HTMLdiv元素设置布尔属性。

以下是切换属性true或false的代码:

$(document).on('click', '.chartPageSensorBox', function () {
    var chartNumber = this.id.charAt(6),
        visibilityIndex = this.id.charAt(9),
        checkBoxToggle = this.id.contentEditable; 
    //the alert below returns default value,  output is: 'true true'
    alert(this.id.contentEditable + " " + checkBoxToggle);
    checkBoxToggle = !checkBoxToggle;
    this.id.contentEditable = checkBoxToggle;
    //the alert output now is: 'false false'
    alert(this.id.contentEditable + " " + checkBoxToggle);
    //The series for the chart successfully turns off because it is false
    allCharts[chartNumber - 1].dyGraph.setVisibility(visibilityIndex, checkBoxToggle);
});

现在的问题是,当我再次单击div时,false仍然是false,并且永远不会变回true,我不明白为什么,因为if语句应该将checkBoxToggle变为true。

编辑#1:清理了代码,但没有修复错误,只是为了让未来的读者更容易阅读。

编辑#2:请参阅下面的代码。核心问题仍然存在。。。

$(document).on('click', '.chartPageSensorBox', function () {
    var chartNumber = this.id.charAt(6),
        visibilityIndex = this.id.charAt(9),
        checkBoxToggle = $(this).prop("contentEditable");
    alert(checkBoxToggle); 
    checkBoxToggle = !checkBoxToggle;
    alert(checkBoxToggle);
    //After the alerts, true becomes false, but false remains false indefinitely. 
    $(this).prop("contentEditable", checkBoxToggle);
    allCharts[chartNumber - 1].dyGraph.setVisibility(visibilityIndex, checkBoxToggle);
});

很少。

  1. 使用this而不是document.getElementById(this.id)
  2. 在检查是否具有属性时,请使用.isContentEditable而不是.contentEditable

    alert(this.isContentEditable + " " + checkBoxToggle);
    
  3. 此外,您需要使用"true"而不是true来设置contentEditable属性。不知道为什么。试试看

最后,更改以下内容:

if (checkBoxToggle) {
    checkBoxToggle = false;
} else {
    checkBoxToggle = true;
}

收件人:

checkBoxToggle = !checkBoxToggle;

简单地说,由于您使用的是jQuery,您只需使用:

$(this).prop("contenteditable");        // Getter
$(this).prop("contenteditable", true);  // Set to true
$(this).prop("contenteditable", false); // Set to false