javascript - 如何使其在 Firefox 以外的所有其他浏览器中工作

标签 javascript jquery cross-browser

我有一个包含数字的选择列表。这些数字从 0 到 30。我想根据当前日期和用户设置的日期相隔的天数来隐藏数字。

因此,如果今天是 2010 年 7 月 28 日,而他们设置为 2010 年 7 月 29 日,那么它应该只显示“0”。

如果日期是 2010 年 7 月 28 日,而他们设置为 2010 年 9 月 20 日,则应该显示 0 到 30。

所以我有这个

  var selectedDate = new Date($('#TextBox').val().replace(/\/(\d\d)$/, "/20$1"));
    var currentDate = new Date();

    var month = currentDate.getMonth() + 1
    var day = currentDate.getDate()
    var year = currentDate.getFullYear()

    currentDate = new Date(month + "/" + day + "/" + year);


    if (isNaN(selectedDate) == false)
    {
        $('#selectList').find('select').attr('disabled', '');

        var diffDays = parseInt((selectedDate  - currentDate) / (1000 * 60 * 60 * 24));

        var Options = $('#selectList').find('option');

        jQuery.each(Options, function (i, value)
        {
            var currentValue = $(this).val();
            if (currentValue == -1)
            {
                // equal to continue;
                return true;
            }
            else if (currentValue >= diffDays)
            {
                $(this).hide();
            }
            else
            {
                $(this).show();
            }
        });
    }

此代码发生在用户选择日期的文本框发生更改时。

这在 FireFox 中工作正常,但在任何其他浏览器中不起作用。我不知道为什么。所有浏览器中均未显示任何错误。

最佳答案

你根本无法隐藏/显示 <option>像这样的跨浏览器元素,您需要有一个备份/隐藏 <select>并仅复制 <option>每次你想要的元素,或者只是禁用 <option>您不希望选择的元素,但这将使它们可见。

克隆部分看起来像这样:

var hiddenSelect = $("#selectList").find('select').clone();
var selectedDate = new Date($('#TextBox').val().replace(/\/(\d\d)$/, "/20$1"));
var currentDate = new Date();

var month = currentDate.getMonth() + 1
var day = currentDate.getDate()
var year = currentDate.getFullYear()

currentDate = new Date(month + "/" + day + "/" + year);


if (isNaN(selectedDate) == false) {
    $('#selectList').find('select').attr('disabled', '');
    var diffDays = parseInt((selectedDate  - currentDate) / (1000 * 60 * 60 * 24));

    var select = $('#selectList').find('select').empty();
    hiddenSelect.children().each(function(i, value) {
        if (value == -1) {
            return true;
        }
        else if (currentValue < diffDays) {
            $(this).clone().appendTo(select);
        }      
    });
}

我们只是将原始版本的克隆副本保存在名为 hiddenSelect 的变量中。 ,清空(通过 .empty() )UI 中可见选项上的选项,然后循环/克隆您想要查看的选项回到该可见选择中。

关于javascript - 如何使其在 Firefox 以外的所有其他浏览器中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3357752/

相关文章:

javascript - 句子中间的省略号

javascript - 如何使用 JS 或 HTML 以编程方式清除浏览器缓存

javascript - 垂直滚动的 html 列表

javascript - FormData 不适用于 Firefox 上的 String

IE11 的 Javascript 问题

javascript - 如何从动态创建的输入中更新总和?

javascript - iOS 平台的 React Native 中加密图像并将其保存在 Gallery 中的方法?

html - 如何安抚 Chrome 的输入显示(图像和文本输入)?

javascript - 构建我的 Electron 应用程序时出错

javascript - 使用单选按钮交替样式表