首页 > 解决方案 > 为什么隐藏/显示事件在 Safari 中不起作用

问题描述

当页面加载时,我希望隐藏所有下拉选项。我使用 CSS 尝试了这个display: none。我尝试使用 jQuery。但是,这些都不适用于 Safari。该代码适用于 Chrome,但不适用于 Safari。

我试过了:

jQuery(document).ready(function ($) {
  $(".product_names option").hide();
  });

jQuery("select").change(function() {
  $(".product_names option").hide();
});
<select class="product_names">
  <option>Select option</option>
  <option>Test1</option>
  <option>Test2</option>
  <option>Test3</option>
  <option>Test4</option>
  <option>Test5</option>
</select>

jQuery(document).on('change', 'select', function () {
    $('.product_names option').hide();
    });

jQuery(document).on('change', 'select', function () {
    $('.product_names option').hide();
    });
<select class="product_names">
  <option>Select option</option>
  <option>Test1</option>
  <option>Test2</option>
  <option>Test3</option>
  <option>Test4</option>
  <option>Test5</option>
</select>

jQuery(document).ready(function() {
      jQuery("select").change(function(){
           $("select option").hide();
      }); 
});

jQuery(document).ready(function() {
      jQuery("select").change(function(){
           $("select option").hide();
      }); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="product_names">
  <option>Select option</option>
  <option>Test1</option>
  <option>Test2</option>
  <option>Test3</option>
  <option>Test4</option>
  <option>Test5</option>
</select>

标签: jqueryhtml

解决方案


我可以确认 Safari 忽略display: noneoption元素。

您最好的选择可能是禁用选项而不是隐藏它们:

$(".product_names").val("").find("option").prop("disabled", true);

如果你真的想隐藏它们,你需要删除它们。如果您想稍后再放,您可以随时将它们放回去:

var options = $(".product_names").find("option").detach();

将它们添加回来:

options.appendTo(".product_names");

推荐阅读