我有一堆选择框用于过滤一个大型复杂表,该表的内容是通过一系列 ajax 查询加载的。随着表格的加载,不仅表格而且选择框过滤器也会更新以反射(reflect)当前可用的选项。由于此时用户可能已经选择了筛选表的选项,因此我有一些代码来保留当前选择的值:
if($('#CourseFilter').length) {
selected = $('#CourseFilter').val();
$('#CourseFilter').replaceWith(sel);
if(selected != '') $('#CourseFilter option[value="'+escape(selected)+'"]').prop('selected', true);
} else {
sel.appendTo('#filters'); // Adding fitler for first time.
}
这适用于大多数过滤器,但有几个过滤器(例如 #CourseFilter
)会重置回默认值,而不是记住当前选择。它认为这是因为这些列表中的值包含特殊字符,例如-
、/
和\
。我试过使用 escape
但它仍然不起作用。有什么想法吗?
最佳答案
您可能正在寻找的内容:
您应该能够设置 sel
的值, 而不是找到正确的 <option>
并手动选择:
sel.val(selected);
如果你想找到合适的<option>
:
您可以通过过滤右边的 <option>
来完全避免转义问题。使用 jQuery.filter :
$('#CourseFilter option').filter(function() {
return $(this).val() === selected;
}).prop('selected', true);
关于javascript - 在 jquery 中转义选择选项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45012708/