.each () помещает слишком много элементов в массив - PullRequest
0 голосов
/ 23 января 2020

Я использую .each () для pu sh и замены html элементов в некоторый визуализированный текст. Однако, когда я проверяю элемент вывода в консоли, он нажимает каждый элемент несколько раз, а не один раз. Я только включил код, где я думаю, что проблема

(function($) {

  $.fn.definitions = function(words) {
    console.log("words: ", words); // returns words array

    var count = 0;
    var html;
    // Iterate over a jQuery object, executing a function for each matched element.
    return this.each(function() {
      var _results = [];
      var _term = words["term"]; //console.log(_term);  //return each definition / word pair object in a single array
      var _this = $(this); //console.log(_this);  //$(this) returns a jQuery object that wraps the element (all jQuery functions)

      if (_term.length > 1) {
        $.each(_term, function() {
          //$.each() function can be used to iterate over any collection, whether it is an object or an array (not just a jQuery object) .

          for (let key in _term) {
            // iterates over all properties of an object returning value only.
            var val = _term[key]; //console.log(val);  //returns each dict def / word pair object individually

            _results.push(
              _this.html(function(index, htmlContent) {
                if (
                  _this
                  .text()
                  .indexOf(val["word"]) >= 0 //word length > 0
                ) {
                  //console.log(key);
                  return (html = define_replace(
                    val["word"],
                    val["definition"],
                    val["kana"],
                    val["romaji"],
                    val["note"],
                    htmlContent,
                    key
                  ));
                }
              })
            );
          } //end for...in
        });

      }
    }); //end  return this.each(function()
  }; //end  $.fn.definitions

  //inject class before and after found word in html
  var define_replace = function(word, def, kan, rom, note, html, key) {
    //console.log(arguments);
    var re;

    return html.replace(
      word + " ",
      '<a data-html="true"' +
      'data-toggle="popover"' +
      'data-title="' + word + '"' +
      'data-content="definition">' +
      word + " " + "</a>",
      "gi"
    );
  }; // end define_replace 
}(jQuery));



$(function() { //can remove function and $words to words                
  var $words = [{
      word: "今日",
      definition: "adjective today, this day, these days, recently, nowadays"
    },
    {
      word: "毎日",
      definition: "every day"
    },
    {
      word: "も",
      definition: "adjective today, this day, these days, recently, nowadays"
    },
    {
      word: "頑張りましょう",
      definition: "verb to persevere, to persist, to keep at it, to hang on, to hold out, to do one\'s best"
    },
  ];

  $('.define').definitions({
    term: $words
  });

}); //end $(function()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="japanese" class="define">毎日 今日 も 頑張りましょう </p>

1 Ответ

1 голос
/ 23 января 2020

У вас есть две петли над элементами _term. $.each() зацикливается на них, а затем вложенный for l oop также перебирает их. Таким образом, вы выполняете итерацию 16 раз вместо 4 раз.

Просто используйте $.each(), чтобы получить один l oop.

(function($) {

  $.fn.definitions = function(words) {
    console.log("words: ", words); // returns words array

    var count = 0;
    var html;
    // Iterate over a jQuery object, executing a function for each matched element.
    return this.each(function() {
      var _results = [];
      var _term = words["term"]; //console.log(_term);  //return each definition / word pair object in a single array
      var _this = $(this); //console.log(_this);  //$(this) returns a jQuery object that wraps the element (all jQuery functions)

      if (_term.length > 1) {
        $.each(_term, function(key, val) {

          _results.push(
            _this.html(function(index, htmlContent) {
              if (
                _this
                .text()
                .indexOf(val["word"]) >= 0 //word length > 0
              ) {
                //console.log(key);
                return (html = define_replace(
                  val["word"],
                  val["definition"],
                  val["kana"],
                  val["romaji"],
                  val["note"],
                  htmlContent,
                  key
                ));
              }
            })
          );
        });

      }
    }); //end  return this.each(function()
  }; //end  $.fn.definitions

  //inject class before and after found word in html
  var define_replace = function(word, def, kan, rom, note, html, key) {
    //console.log(arguments);
    var re;

    return html.replace(
      word + " ",
      '<a data-html="true"' +
      'data-toggle="popover"' +
      'data-title="' + word + '"' +
      'data-content="definition">' +
      word + " " + "</a>",
      "gi"
    );
  }; // end define_replace 
}(jQuery));



$(function() { //can remove function and $words to words                
  var $words = [{
      word: "今日",
      definition: "adjective today, this day, these days, recently, nowadays"
    },
    {
      word: "毎日",
      definition: "every day"
    },
    {
      word: "も",
      definition: "adjective today, this day, these days, recently, nowadays"
    },
    {
      word: "頑張りましょう",
      definition: "verb to persevere, to persist, to keep at it, to hang on, to hold out, to do one\'s best"
    },
  ];

  $('.define').definitions({
    term: $words
  });

}); //end $(function()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="japanese" class="define">毎日 今日 も 頑張りましょう </p>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...