首页 > 解决方案 > 将事件更改为 on.click 以进行搜索

问题描述

我在下面找到了这个片段,它突出显示并跳转到搜索词。当前的代码片段在用户输入的每次击键后进行搜索,这对服务器造成了太大的压力。相反,我希望它mark在用户按下回车键或单击下一步按钮后跳转。我尝试更改以下行,但它破坏了代码。有任何想法吗?

$input.on("input", function() {

$nextBtn.on('click', function() {

代码在这里:

$(function() {

  // the input field
  var $input = $("input[type='search']"),
    // clear button
    $clearBtn = $("button[data-search='clear']"),
    // prev button
    $prevBtn = $("button[data-search='prev']"),
    // next button
    $nextBtn = $("button[data-search='next']"),
    // the context where to search
    $content = $(".content"),
    // jQuery object to save <mark> elements
    $results,
    // the class that will be appended to the current
    // focused element
    currentClass = "current",
    // top offset for the jump (the search bar)
    offsetTop = 50,
    // the current index of the focused element
    currentIndex = 0;

  /**
   * Jumps to the element matching the currentIndex
   */
  function jumpTo() {
    if ($results.length) {
      var position,
        $current = $results.eq(currentIndex);
      $results.removeClass(currentClass);
      if ($current.length) {
        $current.addClass(currentClass);
        position = $current.offset().top - offsetTop;
        window.scrollTo(0, position);
      }
    }
  }

  /**
   * Searches for the entered keyword in the
   * specified context on input
   */
  $input.on("input", function() {
    var searchVal = this.value;
    $content.unmark({
      done: function() {
        $content.mark(searchVal, {
          separateWordSearch: true,
          done: function() {
            $results = $content.find("mark");
            currentIndex = 0;
            jumpTo();
          }
        });
      }
    });
  });

  /**
   * Clears the search
   */
  $clearBtn.on("click", function() {
    $content.unmark();
    $input.val("").focus();
  });

  /**
   * Next and previous search jump to
   */
  $nextBtn.add($prevBtn).on("click", function() {
    if ($results.length) {
      currentIndex += $(this).is($prevBtn) ? -1 : 1;
      if (currentIndex < 0) {
        currentIndex = $results.length - 1;
      }
      if (currentIndex > $results.length - 1) {
        currentIndex = 0;
      }
      jumpTo();
    }
  });
});

工作 JSFiddle 在这里找到:https ://jsfiddle.net/83nbm2rv/

标签: javascriptjquery

解决方案


您可以将其更改$input.on('input')为:

$input.on("keypress", function(e) {
  if (e.which === 13) {
    var searchVal = this.value;
    $content.unmark({
      done: function() {
        $content.mark(searchVal, {
          separateWordSearch: true,
          done: function() {
            $results = $content.find("mark");
            currentIndex = 0;
            jumpTo();
          }
        });
      }
    });
  }
});

这将处理enter文本框中的按下。请参阅此小提琴以获取下一个按钮单击更新:https ://jsfiddle.net/9g4xr765/

基本方法是功能化内容标记并在$input按键上调用它,如果没有结果,也可以在下一次/上一次点击中调用。

但是仍然存在一些问题,例如如果值发生更改,您无法使用下一个/上一个按钮进行搜索,因此需要一些额外的工作。


推荐阅读