我正在使用以下函数,它在 chrome 中完美运行,如果没有重复则返回 true,如果有重复则返回 false 并显示 #error
div。
如果我在 IE11 中运行它,它会将它们全部标记为重复项并显示 #error
div,即使没有任何重复项...
// Check for duplicates
function checkSelect() {
var valid = true;
var atLeastAValue = false;
$("select").css("background-color", "white");
$.each($("select"), function (index, value) {
var others = $("select");
if ($(value.selectedOptions).val() !== "") {
$.each(others, function (otherIndex, otherValue) {
if ($(otherValue.selectedOptions).val() !== "") {
if (index === otherIndex && $(value.selectedOptions).val() === $(otherValue.selectedOptions).val()) {
atLeastAValue = true;
} else if ($(value.selectedOptions).val() === $(otherValue.selectedOptions).val()) {
$(value).css("background-color", "#ff9696");
$(otherValue).css("background-color", "#ff9696");
valid = false;
}
}
});
} else if (!atLeastAValue) {
$(value).css("background-color", "#ff9696");
valid = false;
}
});
if (!valid) {
var $div2 = $("#error");
if ($div2.is(":visible")) { return; }
$div2.show("slow");
setTimeout(function() {
$div2.hide("slow");
}, 10000);
}
return valid;
};
是什么让它与 IE11 不兼容,我该如何让它兼容...
最佳答案
selectionOptions尚未在 IE 中实现。由于您总是将选定的选项传递给 jQuery,因此您可以改用 :selected 选择器。
因此 $(value.selectedOptions)
变为 $(value).find('option:selected')
或 $(value).val()
或只是 value.value
(如果选择是单选)
function checkSelect() {
var valid = true;
var atLeastAValue = false;
$("select").css("background-color", "white");
$.each($("select"), function (index, value) {
var others = $("select");
if ($(value).find('option:selected').val() !== "") {
$.each(others, function (otherIndex, otherValue) {
if ($(otherValue).find('option:selected').val() !== "") {
if (index === otherIndex && $(value).find('option:selected').val() === $(otherValue).find('option:selected').val()) {
atLeastAValue = true;
} else if ($(value).find('option:selected').val() === $(otherValue).find('option:selected').val()) {
$(value).css("background-color", "#ff9696");
$(otherValue).css("background-color", "#ff9696");
valid = false;
}
}
});
} else if (!atLeastAValue) {
$(value).css("background-color", "#ff9696");
valid = false;
}
});
if (!valid) {
var $div2 = $("#error");
if ($div2.is(":visible")) {
return;
}
$div2.show("slow");
setTimeout(function () {
$div2.hide("slow");
}, 10000);
}
return valid;
};
您也可以只使用 $(value).val()
来获取选择元素的值,如果是单选,它将只返回值,如果选择是多选选择然后它将返回一个选定值的数组
更简单的方法可以是
function checkSelect() {
var $selects = $("select").removeClass('duplicate');
$selects.each(function(){
var value = this.value;
$selects.not(this).has('option[value="'+this.value+'"]:selected').addClass('duplicate');
})
var valid = !$selects.hasClass('duplicate');
if (!valid) {
var $div2 = $("#error").stop(true, true);
if ($div2.is(":hidden")) {
$div2.show("slow");
setTimeout(function () {
$div2.hide("slow");
}, 10000);
}
}
return valid;
};
演示:Fiddle
关于javascript - jQuery/Javascript 函数在 Chrome 中有效,但在 IE11 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29113698/