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

时间:2015-10-26 21:41:50

标签: javascript

这看起来非常微不足道,但我不确定它为什么不起作用。

我正在使用div而不是我的Web应用程序的复选框。我正在使用名为“contentEditable”的javascript功能将布尔属性设置为HTML div元素。

以下是切换属性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 个答案:

答案 0 :(得分:2)

很少。

  1. 使用this代替document.getElementById(this.id)
  2. 在检查是否包含该属性时,请使用.isContentEditable代替.contentEditable

    alert(this.isContentEditable + " " + checkBoxToggle);
    
  3. 此外,您需要使用"true"而非contentEditable设置true属性。不知道为什么。所以试试吧!
  4. 最后,更改以下内容:

    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
    
相关问题