Изменение события на on.click для условий поиска - PullRequest
0 голосов
/ 15 октября 2019

Ниже приведен фрагмент кода, который выделяет искомый термин и переходит к нему. Текущий фрагмент ищет после каждого нажатия клавиши, которое вводит пользователь, что создает слишком большую нагрузку на сервер. Вместо этого я хочу, чтобы он набрал 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/

1 Ответ

0 голосов
/ 15 октября 2019

Вы можете изменить $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, а также при следующем / предыдущем щелчке, если нет результатов.

Тем не менее, остаются проблемы, например, если значение изменяется, вы не можете использовать следующую / предыдущую кнопку для поиска, что потребует дополнительной работы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...