如何检查值是否为空?

mar*_*ion 1 javascript jquery

我有一些包含空白选项的选择菜单。当两者都为空白时(通常在第一页加载时),我想显示一些隐藏的 div。

这就是我所拥有的:

$('.variant_options select').each(function() { 
    if ($(this).attr('value') === '') {
        // some code here to show hidden div
        console.log("No options chosen");
    }
});
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用。

编辑 1

对于它的价值,我尝试过这样的事情:

if (!$(this).attr('value'))
Run Code Online (Sandbox Code Playgroud)

这似乎有效,但它破坏了其他地方的功能。

Ja͢*_*͢ck 5

<select>元素没有value属性,因此您需要.val()在元素上使用来确定当前选择的选项是否为空。

if ($(this).val() === '') {
    // value of select box is empty
}
Run Code Online (Sandbox Code Playgroud)

this.value === '' 也应该工作

要检查是否未选择任何选项:

if (this.selectedIndex == 0) {
    // no option is selected
}
Run Code Online (Sandbox Code Playgroud)