2015-10-26 102 views
1

这看起来非常微不足道,但我不知道它为什么不工作。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); 
}); 

现在的问题是,当我再次点击股利,虚假仍假永不变回真,我不理解为什么自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); 
}); 
+5

'的document.getElementById(this.id)'?为什么不使用'this'? –

+0

愚蠢的错误...好点。 – NutellaAddict

+0

我知道。这就是我最初做的......我'扩大'了代码以尝试调试它。 – NutellaAddict

回答

2

几件事情。

  1. 使用this而不是document.getElementById(this.id)
  2. 使用.isContentEditable代替.contentEditable,同时检查它是否具有该属性。

    alert(this.isContentEditable + " " + checkBoxToggle); 
    
  3. 此外,你需要设置使用"true"而不是truecontentEditable财产。不知道为什么。所以试试!

最后,改变如下:

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 
+0

对于downvoted的人,请解释原因... –

+0

Praveen正确,.contentEditable属性是一个字符串,因此if(checkBoxToggle){}将始终为true。 .isContentEditable返回布尔值,所以在这种情况下,这是正确的答案 – sjm

+0

你建议的一切都只是美容。没有任何建议可以解决实际问题。 – JJJ