【问题标题】:Jquery: Convert string to booleanJquery:将字符串转换为布尔值
【发布时间】:2013-07-24 18:16:01
【问题描述】:

我正在从一些隐藏字段中汇集以下值。

var hfEntityBool = $(this).find('input[id*="hfEntityBool"]').val();
if (hfEntityBool) {
    alert(hfEntityBool);
}

无论隐藏字段的值是多少,警报仍会显示。有什么理由吗?

我尝试使用 Boolean(hfEntityBool) 方法以防隐藏字段仍然是字符串,但没有任何改变。

感谢您的帮助

【问题讨论】:

  • 警报显示什么?
  • @LeeMeador OP 表示无论hfEntityBool 是true 还是false 都会显示警报:)
  • hfEntityBool 在if 块中被评估时的值是多少?查看this for a reference
  • 第三行代码有一个alert() 调用。该警报的弹出框中会显示什么文本?

标签: jquery hidden-field


【解决方案1】:

这取决于您期望隐藏字段中的值。

我会这样做:

var hfEntityBool = $(this).find('input[id*="hfEntityBool"]').val() == "true";
if (hfEntityBool) {
    alert(hfEntityBool);
}

【讨论】:

    【解决方案2】:

    你试过了吗:

    if(hfEntityBool.length){...} // (or hfEntityBool.length > 0)
    

    控制台对此显示什么:

    console.log('nb char of hfEntityBool : '+hfEntityBool.length);//before if
    

    【讨论】:

      猜你喜欢
      • 2018-09-07
      • 1970-01-01
      • 2012-03-10
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多