删除一个元素后,确定表单上有多少个选择元素

时间:2012-02-28 04:27:16

标签: jquery

全部, 我正在使用以下代码删除一些使用jQuery的选项:

$('#other_liked_vendors option[value=' + clicked_id + ']').remove();
length = $("#other_liked_vendors").val().length;
alert(length);
if($("#other_liked_vendors").val().length === 0){
    $("#view_other_liked_vendors").hide();
}

我基本上试图说最后一个选择元素是否已被删除然后我想隐藏选择元素所在的div。有人能告诉我如何正确检查这个吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用jQuery对象的.length属性来查看匹配的元素数量。所以:

if ($('#other_liked_vendors option').length == 0) {
    // all options have been removed
}

您试图使用.val()的长度,这是当前所选选项的值的字符串长度...

答案 1 :(得分:1)

$("#other_liked_vendors").val().length会为您提供所选元素的length选择值。

您应该使用此选项,它会在select元素中找到option个元素并检查其length属性。

if ($('#other_liked_vendors option').length == 0) {
    $("#view_other_liked_vendors").hide();
}

答案 2 :(得分:0)

你可以这样做:


if($('#other_liked_vendors option').size() == 0) {
......

或者更好一个


if($('#other_liked_vendors option').length == 0) {
......