首页 > 解决方案 > 在下拉列表中,将 optgroup 名称设置为 JS 在 Firefox 中不起作用的选定选项文本

问题描述

我有 javascript 将select下拉列表中显示的选定文本设置为选定选项的<optgroup>标签,但是当下拉列表打开时,它会将存储的文本显示data-content为标签下的选项文本<optgroup>。它在 Chrome 中运行良好,但在 Firefox 中中断。在 Firefox 中单击选择时,它开始打开和关闭的速度非常快,无法进行选择。我注意到,当我注释掉$(this).blur闪烁停止的部分时,js 显然会中断。谢谢你尽你所能的帮助!

您可以在此处查看 jsfiddle

这是HTML:

<select id="car_choice">
  <optgroup label="Truck">
    <option data-value="truck" data-title="Truck" data-content="A description of a truck">
      Truck
    </option>
  </optgroup>
  <optgroup label="Car">
    <option data-value="car" data-title="Car" data-content="A description of a car">
      Car
    </option>
  </optgroup>
</select>

这是JS:

$('#car_choice option:selected').html($('#car_choice option:selected').attr('value'));

$("#car_choice").on('change mouseleave', function(){
  $('#car_choice option').each(function(){
    $(this).html($(this).attr('data-title'));
  });
  $('#car_choice option:selected').html($('#car_type_choice option:selected').attr('data-title'))
  $(this).blur();
});

$('#car_choice').on('focus', function(){
  $('#car_choice option').each(function(){
    $(this).html( $(this).attr('data-content'));
  });
});

标签: javascriptjqueryhtmlfirefoxcross-browser

解决方案


一种粗略的解决方案,但我在这里解决了

$('#assignment_type_choice option:selected').html($('#assignment_type_choice option:selected').attr('value'));

var browser;
if (navigator.userAgent.match(/Chrome/i)) {
    browser = "chrome";
}
else {
    browser = "other";
}

$("#assignment_type_choice").on('click mouseup', function(){
    if(browser === "other"){
    $('#assignment_type_choice').each(function(){
      $(this).text($(this).attr('data-title'));
    });
    $('#assignment_type_choice option:selected').html($('#assignment_type_choice option:selected').attr('data-title'))
   };
 });


$("#assignment_type_choice").on('change mouseleave', function(){
    console.log("browser is " + browser)
    if(browser === "chrome"){
    $('#car_choice option').each(function(){
      $(this).text($(this).attr('data-title'));
    });
    $('#assignment_type_choice option:selected').html($('#assignment_type_choice option:selected').attr('data-title'))
 };
});

$('#assignment_type_choice').on('mousedown', function(){
  $('#assignment_type_choice option').each(function(){
    $(this).text( $(this).attr('data-content'));
  });
});

推荐阅读