去除包裹在<option>标签周围的<span>标签

3

我试图在一个下拉列表中隐藏和显示标签,最初我成功地让它在除Internet Explorer之外的所有地方工作。然后我发现将需要隐藏的选项包含在<optgroup>标签中可以解决IE的问题。但是我现在遇到了一个问题,因为我编写的代码也删除了它们所包含的下拉列表。我做错了什么?以下是目前的代码:

function GetMonthsForSelectedYear() {
    var selectedYear = $("#DropDownListYear option:selected").text(),
        currentYear = (new Date()).getFullYear(),
        currentMonth = (new Date()).getMonth() + 1;

    $("#DropDownListMonth option").each(function() {
        if (selectedYear == currentYear) {
            var option = $(this).index();
            if (option < currentMonth) {
                $(this).wrap('<span>').hide();
            }
        } else {
            $(this).unwrap("<span>").show();
        }
    });
}

$("#DropDownListYear").change(function() {
   GetMonthsForSelectedYear();
});​

以下是JSFiddle链接:

http://jsfiddle.net/MGGh9/1/

谢谢。


这是因为在else条件语句中,$(this)没有得到正确的值。在if语句后,您关闭了标签两次。 - Tarun
2个回答

2
相反,您可以直接使用以下内容:
$("#DropDownListMonth option[value=" + title + "]").hide();

当你使用<span>包装时,它会将整个<select>都包装起来,而不仅仅是那个<option>。这是一种预期的行为。此外,在select标签内除optionoptgroup以外的任何其他内容都不是正确的方法。

在您的代码中:

function GetMonthsForSelectedYear() {
    var yearOfEntry = $("#DropDownListYear option:selected").text(),
        currentYear = (new Date()).getFullYear(),
        currentMonth = (new Date()).getMonth() + 1;

    $("#DropDownListMonth option").each(function() {
        if (yearOfEntry == currentYear) {
            var option = $(this).index();
            if (option < currentMonth) {
                $(this).hide();               // «--------- This one
            }
        } else {
            $(this).show();                   // «--------- This one
        }
    });
}

$("#DropDownListYear").change(function() {
   GetMonthsForSelectedYear();
});​

Fiddle: http://jsfiddle.net/MGGh9/2/

还可以参考以下内容:

  1. 如何使用CSS隐藏<select>菜单中的<option>?
  2. 如何使用JavaScript隐藏<select>菜单中的选项?(跨浏览器)

1
这不是正确的方式。实际上,这是无效的HTML标记。 - feeela
以上的评论是针对什么的?@user1862653 这有帮助吗? - Praveen Kumar Purushothaman
啊,解决方案就在你发布的链接里:如何使用JavaScript隐藏选择选项?(跨浏览器)。谢谢。 - user1862653

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接