我不敢相信,但是我找到了一些JS代码,它们在IE 11中可以完美地工作,但在Chrome(版本81)中却不能工作。
我正在更新另一个选择,同时保持选项排序。所以我有一个功能:
/**
* Move the options defined by <sel> from select tag <from> to select tag <to>
* @param from The source SELECT tag jQuery object
* @param to The destination SELECT tag jQuery object
* @param sel Either: "option" for all, or "option:selected"
*/
function moveOpt(from, to, sel) {
var opts = from.children(sel).removeAttr('selected').remove().get();
opts = opts.concat(to.children('option').remove().get());
opts.sort(function (a, b) {
return a.value.localeCompare(b.value);
});
to.append(opts);
/*
// Chrome doesn't re-render the opts until they are selected and then focus is lost ???
window.setTimeout(function() {
to.children('option').attr('selected', 'selected').trigger('click');
from.trigger('focus');
to.children('option').removeAttr('selected');
}, 1);
*/
}
这在IE 11中非常有效,但是在chrome中,选项被移动了,但是您无法在浏览器中看到它们。它们之所以存在,是因为如果您“检查” SELECT元素,所有的OPTION标记都在那里,并且也执行$(to).children().length
显示正确的数字。
如果我取消对丑陋的HACK(window.setTimeout()
呼叫)的注释,那么Chrome最终将正确显示选项。但是必须这样做。我一定做错了什么。有人知道那是什么吗?
[Here is a JS fiddle showing the issue-在IE中运行(只读模式)显示它可以运行,而Chrome无法运行。
我尝试将jQuery从1.10.2升级到3.5.0,但仍然无法正常工作。
也正如@ZacharyYaro指出的那样,它可以在Chrome 80中使用,但不适用于81。
更改此:
to.append(opts);
为此:
var toElm = to.get()[0];
$.each(opts, function(i,v) { toElm.appendChild(v); });
解决问题。
(因为它对您有用,所以重新提交我的评论作为答案)看来您的Fiddle也可以在Chrome 80中使用,然后在Chrome 81中可以使用。using the built-in selectElement.add
function instead of jQuery (JSFiddle)在Chrome 81中可以使用,因此Chrome 81似乎破坏了jQuery selectElement.add
函数使用的功能。