简体   繁体   English

将bool值设置为输入并通过javascript / jquery获取字符串类型

[英]Setting bool value to input and getting string type via javascript/jquery

When I get a value or set a value (from the server side, for example) for an input that is a boolean type it comes as "True" or "False" instead of true or false. 当我得到一个值或者为一个布尔类型的输入设置一个值(例如从服务器端)时,它变为“True”或“False”而不是true或false。

For example: 例如:

//"True"
var isDated = $('.someClass').val();


//will not pass because isDated is a string
if (isDated == true){
    console.log("passed");
}

Why does this happend? 为什么会这样? Which is the best way to avoid this? 哪种方法可以避免这种情况?


EDIT: 编辑:

I've found a blog that has a solution to avoid this problem: http://www.peterbe.com/plog/data-and-attr-in-jquery 我找到了一个可以避免这个问题的解决方案的博客: http//www.peterbe.com/plog/data-and-attr-in-jquery

Below a prototype method called .toBoolean() to validate true/false when it comes as a string based on some responses from this post: 在一个名为.toBoolean()的原型方法下面,根据这篇帖子的一些回复,当它作为字符串出现时验证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;
};

If you want to know why C# outputs True and False instead of the lowercase versions, see this question . 如果您想知道为什么C#输出TrueFalse而不是小写版本,请参阅此问题

If you want to know why it's not converted to a boolean value, it's because all <input> elements' values are considered text by JavaScript. 如果你想知道它为什么没有转换为布尔值,那是因为所有<input>元素的值都被JavaScript视为文本。 It's up to you to convert it into another type. 您可以将其转换为其他类型。 With checkboxes/radio buttons that's already done by using the .checked attribute (for jQuery, either $('.someClass').is(':checked') or $('.someClass').prop('checked') will work). 使用复选框/单选按钮已经通过使用.checked属性完成(对于jQuery, $('.someClass').is(':checked')$('.someClass').prop('checked')将工作)。 Otherwise, the best way would be comparing the value to a string, and using that, for example: if ($('.someClass').val().toLowerCase() === 'true') . 否则,最好的方法是将值与字符串进行比较,并使用它,例如: if ($('.someClass').val().toLowerCase() === 'true')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM