【问题标题】:Alert when it returns to first occurence当它返回到第一次出现时发出警报
【发布时间】:2018-11-09 02:42:49
【问题描述】:

我正在使用 markjs 插件,特别是使用带有跳转到匹配示例的搜索栏

顶部有一个输入栏,我们输入文本并点击搜索。插件突出显示单词,然后我们跳转到带有按钮的匹配项。

我想在它返回到第一次出现时做一个简单的javascript警报,我该怎么做?

JS 代码:

$(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();
    }
  });
});

JS Fiddle

【问题讨论】:

    标签: javascript jquery search highlight


    【解决方案1】:

    您可以在下一个和上一个按钮的点击事件中设置条件

    if(currentIndex == 0){
       alert('this is first');
    }
    

    JSFiddle for reference

    【讨论】:

    • 感谢您的回答。虽然它在搜索时有效,但每次在搜索框中输入字母时都会收到警报,这不是很方便,对吧?
    • 我已经更新了小提琴链接。现在检查。在点击事件中添加了条件,而不是在 jumpTo 函数中添加了条件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多