【问题标题】:Removing <span> tags that are wrapped around <option> tags移除包裹在 <option> 标签周围的 <span> 标签
【发布时间】:2012-11-17 10:35:21
【问题描述】:

我正在尝试在下拉列表中隐藏和显示标签,我最初设法在 Internet Explorer 之外的所有内容中工作。然后我发现将需要隐藏在标签中的选项包装起来解决了 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 语句后关闭标签 2 次​​span>

标签: javascript jquery asp.net jquery-selectors


【解决方案1】:

你可以直接使用这个:

$("#DropDownListMonth option[value=" + title + "]").hide();

当您包装 &lt;span&gt; 时,它会包装整个 &lt;select&gt;,而不仅仅是 &lt;option&gt;。这是预期的行为。此外,在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();
});​

小提琴:http://jsfiddle.net/MGGh9/2/

同时检查:

  1. How to hide a <option> in a <select> menu with CSS?
  2. How can I hide select options with JavaScript? (Cross browser)

【讨论】:

  • "这不是正确的方式" 嗯,实际上是无效的 HTML 标记……
  • 嗯,上面的评论是为了? @user1862653 这有帮助吗?
  • 啊,解决方案在您发布的链接中:如何使用 JavaScript 隐藏选择选项? (跨浏览器)。谢谢。
  • 哦,太好了。 :) 欢迎。 :D
【解决方案2】:

请注意,根据 HTML 规范 (http://www.w3.org/TR/html5/forms.html#the-select-element),&lt;select&gt; 应仅包含 &lt;option&gt;&lt;optgroup&gt; 或脚本支持元素。因此,您应该避免使用无效的 &lt;span&gt; 包装器,而只需删除和恢复您的 &lt;option&gt; 元素。

看到这个答案 - https://stackoverflow.com/a/24439289/1766230 - 这个问题 - How to hide a <option> in a <select> menu with CSS?.

【讨论】:

    猜你喜欢
    • 2011-12-26
    • 2019-01-28
    • 1970-01-01
    • 2017-08-19
    • 2013-09-15
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多