代码之家  ›  专栏  ›  技术社区  ›  rn605435

返回到第一次出现时发出警报

  •  1
  • rn605435  · 技术社区  · 6 年前

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

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

    当它返回到 首次发生 ,我该怎么做?

    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

    1 回复  |  直到 6 年前
        1
  •  2
  •   Savan S    6 年前

    您可以在“下一步”和“上一步”按钮的单击事件中设置条件

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

    JSFiddle for reference