在 jquery 中转义 select 选项值

Escaping select option values in jquery

我有一堆 select 框用于过滤大型复杂 table,其内容通过一系列 ajax 查询加载。随着 table 的加载,不仅 table 还会更新 select 框过滤器以反映当前可用的选项。由于此时使用可能已经有 selected 选项来过滤 table,我有一些代码来保留当前 selected 值:

    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,重置回默认值而不是记住当前的 selection。它认为这是因为这些列表中的值包含特殊字符,例如 -/\。我试过使用 escape 但它仍然不起作用。有什么想法吗?

您可能要查找的内容:

您应该能够只设置 sel 的值,而不是找到正确的 <option> 并手动选择:

sel.val(selected);

如果你想找到合适的<option>:

您可以通过使用 jQuery.filter:

过滤右侧 <option> 来完全避免转义问题
$('#CourseFilter option').filter(function() {
  return $(this).val() === selected;
}).prop('selected', true);

无需查找每个 <option>,因为 val() 既是 getter 又是 setter。

只需使用 val() 设置新值 <select>

if($('#CourseFilter').length) {
    selected = $('#CourseFilter').val();
    $('#CourseFilter').replaceWith(sel);
    sel.val(selected);
} else {
    sel.appendTo('#filters'); // Adding fitler for first time.
}