【问题标题】:Can I do an if else in a Javascript forEach loop?我可以在 Javascript forEach 循环中执行 if else 吗?
【发布时间】:2021-02-14 18:30:18
【问题描述】:

在这里学习!我正在尝试为包含人员列表的 html 表创建(名称)搜索。我给表体中的每一行都赋予了row-body 的ID 和data-name 的数据属性。对于每一行,我想检查是否可以在名称中找到搜索文本,如果可以,则应该显示该行。否则,该行应该隐藏。 这是我的代码。如何实现 if/else?

    $("#search-box").on('keyup', function () {

        const search = $("#search-box").val();

        $("#body-row").forEach($("#body-row"), if (CheckMatch($(this).data("name"), search)) {
            $(this).show();
        }
        else {
            $(this).hide();
        })

    function CheckMatch(n, s) {
        const name = n.toLowerCase();
        const search = s.toLowerCase();
        return name.includes(search);
    }

【问题讨论】:

  • 不,你不能传递if 声明。您必须传递一个回调函数。当然你可以把if/else放在那个函数里面。但是请注意,在大多数情况下,使用 for … of 循环比使用 forEach 容易得多。

标签: javascript if-statement foreach


【解决方案1】:

首先要做的是使用类而不是 ID - 单个文档中的重复 ID 是无效的 HTML。

虽然您可以通过编写适当的回调来做到这一点(使用适当的名称,.each - .forEach 用于数组、集合和映射,而不是 jQuery 对象):

$(".body-row").each(function() {
  if (CheckMatch($(this).data("name"), search)) {
    $(this).show();
  } else {
    $(this).hide();
  }
});

使用.toggle会更方便:

$(".body-row").each(function() {
    $(this).toggle(CheckMatch($(this).data("name"), search));
});

【讨论】:

    【解决方案2】:

    一个小sn-p,供其他SO用户轻松理解问题和解决方案。

    $("#search-box").on("keyup", function() {
    
      let searchVal = $("#search-box").val();
      $(".list-item").each(function() {
        if (checkMatch(searchVal, $(this).text())) {
          $(this).show();
        } else {
          $(this).hide();
        }
    
        // $(this).toggle(checkMatch(searchVal, $(this).text()))
      });
    });
    
    
    function checkMatch(val, item) {
      return item.toLowerCase().includes(val.toLowerCase());
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" id="search-box">
    
    <ul>
      <li class="list-item">Apple</li>
      <li class="list-item">Mango</li>
      <li class="list-item">Banana</li>
      <li class="list-item">Berry</li>
      <li class="list-item">Appricot</li>
      <li class="list-item">Grapes</li>
      <li class="list-item">Guava</li>
      <li class="list-item">Watermelon</li>
      <li class="list-item">Melon</li>
      <li class="list-item">Pineapple</li>
    </ul>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 2020-03-20
      相关资源
      最近更新 更多