1

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

这就是我所拥有的:

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

这似乎不起作用。

编辑 1

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

if (!$(this).attr('value'))

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

4

5 回答 5

5

<select>元素没有value属性,所以需要.val()在元素上使用来判断当前选中的选项是否为空。

if ($(this).val() === '') {
    // value of select box is empty
}

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

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

if (this.selectedIndex == 0) {
    // no option is selected
}
于 2013-03-26T10:37:41.000 回答
1

你可以简单地这样做:

$('.variant_options select').each(function () {
    if ($.trim($(this).val()) === '') {
        // some code here...
    }
});
于 2013-03-26T10:53:39.380 回答
1

您可以使用以下方法执行此操作:

if($(this).val() === '') {
  // value is empty
}

我也相信以下几点:

if(!$(this).prop('value')) { 
  // It's empty 
}
于 2013-03-26T10:36:51.750 回答
0

如果您有空格,请使用此技巧:

if ($.trim($(this).val()) === '') { ...
于 2013-03-26T10:43:24.643 回答
0

jQuery 可以通过使用检查值$(this).val()

所以你会这样做 if ($(this).val === '')`

如果你想检查其他属性,比如 href 或 src,你可以这样做

if ($(this).attr('href') === ''

于 2013-03-26T10:37:59.707 回答