将布尔值设置为输入并通过 javascript/jquery 获取字符串类型
Setting bool value to input and getting string type via javascript/jquery
当我为布尔类型的输入获取值或设置值(例如,从服务器端)时,它显示为 "True" 或 "False" 而不是 true 或 false .
例如:
//"True"
var isDated = $('.someClass').val();
//will not pass because isDated is a string
if (isDated == true){
console.log("passed");
}
为什么会这样?
避免这种情况的最佳方法是什么?
编辑:
我找到了一个博客,其中包含避免此问题的解决方案:
http://www.peterbe.com/plog/data-and-attr-in-jquery
下面是一个名为 .toBoolean() 的原型方法,用于根据此 post 的一些响应以字符串形式验证 true/false:
String.prototype.toBoolean = function ()
{
var dictionary = { "True": true, "False": false };
return dictionary[this];
};
Boolean.prototype.toBoolean = function () {
return this;
};
Number.prototype.toBoolean = function ()
{
if (this) {
return true;
}
return false;
};
如果您想知道为什么 C# 输出 True
和 False
而不是小写版本,请参阅 this question。
如果您想知道为什么它没有转换为布尔值,那是因为所有 <input>
元素的值都被 JavaScript 视为文本。将其转换为另一种类型取决于您。对于已经使用 .checked
属性完成的 checkboxes/radio 按钮(对于 jQuery,$('.someClass').is(':checked')
或 $('.someClass').prop('checked')
都可以)。否则,最好的方法是将值与字符串进行比较,然后使用它,例如:if ($('.someClass').val().toLowerCase() === 'true')
.
当我为布尔类型的输入获取值或设置值(例如,从服务器端)时,它显示为 "True" 或 "False" 而不是 true 或 false .
例如:
//"True"
var isDated = $('.someClass').val();
//will not pass because isDated is a string
if (isDated == true){
console.log("passed");
}
为什么会这样? 避免这种情况的最佳方法是什么?
编辑:
我找到了一个博客,其中包含避免此问题的解决方案: http://www.peterbe.com/plog/data-and-attr-in-jquery
下面是一个名为 .toBoolean() 的原型方法,用于根据此 post 的一些响应以字符串形式验证 true/false:
String.prototype.toBoolean = function ()
{
var dictionary = { "True": true, "False": false };
return dictionary[this];
};
Boolean.prototype.toBoolean = function () {
return this;
};
Number.prototype.toBoolean = function ()
{
if (this) {
return true;
}
return false;
};
如果您想知道为什么 C# 输出 True
和 False
而不是小写版本,请参阅 this question。
如果您想知道为什么它没有转换为布尔值,那是因为所有 <input>
元素的值都被 JavaScript 视为文本。将其转换为另一种类型取决于您。对于已经使用 .checked
属性完成的 checkboxes/radio 按钮(对于 jQuery,$('.someClass').is(':checked')
或 $('.someClass').prop('checked')
都可以)。否则,最好的方法是将值与字符串进行比较,然后使用它,例如:if ($('.someClass').val().toLowerCase() === 'true')
.