【问题标题】:JQuery filter for anchor text OR title attribute用于锚文本或标题属性的 JQuery 过滤器
【发布时间】:2019-11-25 14:58:58
【问题描述】:

我正在尝试过滤标题或锚文本,以便例如“lala2”或“text2”或“2”会切换其他人(在这种情况下为 1)...我想要不包含要消失的字符串。

<input id="myInput" type="text" placeholder="Search..">

<div id="myList">
  <a class="someclass" title="title text lalalala1" href="blah.com">some anchor text1</a>
  <a class="someclass" title="title text lalalala2" href="blah2.com">some anchor text2</a>
  etc       
</div>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myList a").filter(function() {
      $(this).toggle($(this).text.toLowerCase().indexOf(value) > -1)
    });
  });
});

试过了: 过滤 this.title

$("#myList a, #myList a[title]").filter(function() 

有和没有 $(this).toggle.parent() 还有其他一些事情。 它适用于锚内的文本,即切换不包含“值”的锚,但不能让它为锚标题属性和直接锚文本做到这一点。

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

变化:
• keyup → input,它的效果更可预测 - 即使您同时按下多个键,也适用于复制粘贴。
• filter → each — 只需要任何循环,但不需要过滤元素列表。
• $(this).text().toLowerCase() — 在 text() 中添加了括号 — 这是一个 jQuery 函数。
• includes() — 原生 JavaScript 字符串方法。检查一个字符串是否包含另一个字符串。如果您只想检查而不是获取它的索引,则最好使用它。返回true 或false
• || — 在布尔表达式中表示“或”(顺便说一下 &amp;&amp; — “与”)

$("#myInput").on("input", function() {
  var value = $(this).val().toLowerCase();

  $("#myList a").each(function() {
    $(this).toggle(
      $(this).text().toLowerCase().includes(value) ||
      $(this).attr('title').toLowerCase().includes(value)
    );
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input id="myInput" type="text" placeholder="type 'lala2'...">

<div id="myList">
  <a class="someclass" title="title text lalalala1" href="blah.com">some anchor text1</a>
  <a class="someclass" title="title text lalalala2" href="blah2.com">some anchor text2</a> etc
</div>

【讨论】:

  • 太棒了,正是需要的东西和很好的解释。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多