Javascript布尔值true变为false,false不会变为true
Javascript boolean true turns false, false does not turn true
这看起来非常琐碎,但我不确定为什么它不起作用。
我的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);
});
很少。
- 使用
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
相关文章:
- JavaScript-切换“;全部检查”;复选框true/false
- true==false以某种方式计算为true
- Javascript似乎在说true ==false
- JavaScript onkeydown, return true,false
- 从异步函数返回true/false以用于同步if()
- 函数返回undefined而不是true/false
- 为什么true/true是1,true/false是无穷大,false/true是0,false/false是NaN
- 检查对象数组是否包含布尔值true/false
- 函数:根据字符串中是否存在子字符串返回 True/False
- 如何将 ng-show 与控制器中返回 true/false 的函数一起使用
- 在input.checked=true/false _without_ jQuery上触发一个事件
- jQuery javascript未正确返回true/false
- 如何从嵌套的jquery回调函数中返回true/false
- 如何在骨干模型属性中设置布尔值true/false
- 如何使用angular或javascript在基于true/false返回的html中显示值
- 基于true/false变量显示/隐藏进度条
- Node.js在返回true/false时停止函数
- 是否可以将true/false值传递给ajax函数
- 根据Webix中的复选框值编辑true/false
- Meteor:设置车把变量true/false