[英]Javascript boolean true turns false, false does not turn true
這看起來非常瑣碎,但我不確定為什么它不起作用。
我在我的Web應用程序中使用div而不是復選框。 我正在使用一種名為“ 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);
});
一些事情。
this
代替document.getElementById(this.id)
。 檢查.isContentEditable
而不是.contentEditable
同時檢查其是否具有屬性。
alert(this.isContentEditable + " " + checkBoxToggle);
"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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.