【问题标题】:style="display:none" is not working. Jquery toggle()style="display:none" 不起作用。 jQuery 切换()
【发布时间】:2022-01-10 21:39:25
【问题描述】:

我正在尝试过滤一个 div,它将style="sidplay:none" 分配给不在搜索结果中的所有元素,并且它工作正常,但该属性没有隐藏该元素!

Image here (direct image not available for me)

我的代码

WikiOption.Elements.searchInput.on("input", (thisx)=> {
    
    var val = $(thisx.target).val();
    $(".toc-wrap h3").each(function () {
        $(this).toggle($(this).text().toLowerCase().includes(val));
    });
});

【问题讨论】:

  • 因为您有一些具有更高优先级的 css 属性,例如 (!important)。例如:显示:块!重要;您的问题与 jquery 代码无关。这是css
  • 什么是WikiOption.Elements.searchInput?此外,提供的代码中没有任何内容会更改styles
  • 将其视为一个元素

标签: javascript jquery display


【解决方案1】:

.toggle() 不是在您的情况下使用的正确方法。如果下一个输入事件触发并且<h3> 再次匹配,那么它将变回原来的状态。使用if/else 语句和.show().hide() 方法。

此外,如果您 Backspace 并将 <input> 留空,则不会触发 input 事件,因此会添加 keyup 事件处理程序。

$('.search').on('input', function(e) {
  const txt = $(e.target).val().toLowerCase();
  $('.toc-wrap h3').each(function() {
    if ($(this).text().toLowerCase().includes(txt)) {
      $(this).show();
    } else {
      $(this).hide();
    }
  });
});

$('.search').on('keyup', function(e) {
  if (e.keyCode === 8 && $(this).val() === '') {
    $('.toc-wrap h3').hide();
  }
});
h3 {
  display: none
}
<input class='search' type='search'>
<article class='toc-wrap'>
  <h3>ABCDEFGHIJ</h3>
  <h3>klmnopqrst</h3>
  <h3>uvwxyz</h3>
  <h3>aAbBcC</h3>
</article>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多