gpt4 book ai didi

jquery - $(select).val().length of null 给出错误

转载 作者:行者123 更新时间:2023-12-01 02:40:55 25 4
gpt4 key购买 nike

我的表单中有一个选择对象,使用 Bootstrap-select.js 插件设置样式。当我初始化选择框并尝试获取它的值时,它是 null ,直到我选择一个选项。在我的脚本中我使用:-

$(select).val().length

但是,当 $(select).val()null 时,会出现错误。我真的很想得到一个0

我该怎么做?

最佳答案

尝试:-

($(select).val() || '').length

Logical Operators

Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

Examples of expressions that can be converted to false are:

  • null
  • NaN
  • 0
  • empty string ("")
  • NaN
  • undefined

演示

var length = ($('select').val() || '').length;

console.log('length: ' + length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select>

<select>

关于jquery - $(select).val().length of null 给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37882597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com