jQuery过滤选择选项不适用于Safari(但适用于Chrome和FF) [英] jQuery filtering select options does not work in Safari (but works in Chrome and FF)

查看:256
本文介绍了jQuery过滤选择选项不适用于Safari(但适用于Chrome和FF)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些下拉菜单的表单,第一个选定的下拉菜单将用于过滤第二个下拉菜单的选择(以限制它们).以下代码在FF和Chrome中正常运行,但在Safari(至少11.1.2版以上)中无效:

I have a form with some dropdowns, and the first selected dropdown will serve to filter the second dropdown's choices (to limit them). The following code works just fine in FF and Chrome but will not work in Safari (version 11.1.2 at least):

if(~jQuery(this).attr('id').indexOf('5b0ad35592224') && ~jQuery(this).attr('id').indexOf(jQuery(this).closest('tr').attr('data-id'))) {
        var vallie = jQuery(this).val();
        var sub = jQuery('[id*="'+jQuery(this).closest('tr').attr('data-id')+'-field_5b0ad39f92225"]');
        console.log(sub);
        jQuery('option', sub).filter(function(){
            if (~jQuery(this).val().indexOf(vallie) || jQuery(this).val() === 'Choisir') {
                jQuery(this).show();
            } else {
                jQuery(this).hide();
            }
        });
      jQuery(sub).val('Choisir');  
    };

奇怪的是,当我控制台记录valliesubjQuery(this).val().indexOf(vallie)的返回值时,它们在所有浏览器中都是相同的.我很困惑为什么Safari无法在第二个下拉列表中过滤选项(它只显示所有选项)

The odd thing is when I console log the values returned for vallie or sub or jQuery(this).val().indexOf(vallie) they are the same in all browsers. I am stumped as to why Safari does not filter the options in the second dropdown (it just shows all the options)

推荐答案

感谢@charlietfl提醒我以下事实:隐藏选项不受普遍支持.这是我最终使用的解决方案:

Thanks to @charlietfl for alerting me to the fact that hiding options is not universally supported. Here is the solution I ended up going with:

  1. 我将选项分为单独的js对象
  2. 然后我从第一个下拉列表中检查值,并使用该值来获取正确的菜单对象
  3. 然后我清空现有的(完整)菜单,然后从适当的对象中附加选项.

这是实际的代码:

if(~jQuery(this).attr('id').indexOf('5b0ad35592224') && ~jQuery(this).attr('id').indexOf(jQuery(this).closest('tr').attr('data-id'))) {
  var vallie = jQuery(this).val();
  var thismenu = menu_portes; // set default menu object
  if (vallie === 'Tiroir') {thismenu = menu_tiroirs } else if (vallie === 'Côté') {thismenu = menu_cotes }
  var $sub = jQuery('[id*="'+jQuery(this).closest('tr').attr('data-id')+'-field_5b0ad39f92225"]');

  $sub.empty(); // remove old options
  $sub.append(jQuery('<option>', { value: 'Choisir', text: 'Choisir'})); // add Choisir at top
  jQuery.each(thismenu, function(key,value) { // loop through my object options
    $sub.append(jQuery("<option></option>").attr("value", key).text(value)); //append options from my menu object
  });
  jQuery($sub).val('Choisir'); // set menu to Choisir 
  };

这篇关于jQuery过滤选择选项不适用于Safari(但适用于Chrome和FF)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆