Boostrap popover не работает с html инъекцией - PullRequest
1 голос
/ 21 января 2020

Я пытаюсь создать динамические c всплывающие окна, которые генерируются из массива словаря, который вставляет HTML в существующий текст на странице. Первоначально код использовался для всплывающих подсказок и работал хорошо, но сейчас я пытаюсь перейти на всплывающие окна. Однако html не вводит, и я застрял с этим. Цель состоит в том, чтобы нажать на слово и получить всплывающее окно определения et c. У меня также есть стандартный поповер на той же странице, который работает правильно. Я не получаю никаких ошибок в консоли: (

//script.js
$(function() {
  var $words = [

    {
      word: "ね",
      kana: "",
      romaji: "ne",
      definition: "n postposition<br>indicates emphasis, agreement, request for confirmation, etc., is it so, hey, come on, listen, not",
      note: ""
    },
    {
      word: " 動画",
      kana: "どうが",
      romaji: "douga",
      definition: "video, movie, moving picture, animation, animated cartoon, in-betweens (animation)",
      note: ""
    },
    {
      word: " 今日",
      kana: "きょう",
      romaji: "kyou",
      definition: "adjective today, this day, these days, recently, nowadays",
      note: ""
    },
    {
      word: "毎日",
      kana: "まいにち",
      romaji: "mainichi",
      definition: "every day",
      note: ""
    },
    {
      word: "も",
      kana: "",
      romaji: "mo",
      definition: "adjective today, this day, these days, recently, nowadays",
      note: " te form"
    },
    {
      word: "頑張りましょう",
      kana: "がんばりましょう",
      romaji: "ganbarimashou",
      definition: "verb to persevere, to persist, to keep at it, to hang on, to hold out, to do one\'s best",
      note: "lets do"
    },
  ];
  $('.define').definitions({
    term: $words
  });

}); //end $(function()


$(document).ready(function() {
  $('[data-toggle="popover"]').popover();
});

/*==================js/jquery.define.js============================*/

var html;
$.fn.definitions = function(words) {
  //$.fn alias for jQuery.prototype extends jQuery with your own functions

  //console.log("words: ", words); // returns words array

  var count = 0;

  // 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);  

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

        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()
                .toUpperCase()
                .indexOf(val["word"].toUpperCase()) >= 0
              ) {
                //console.log(html);
                return (html = define_replace(
                  val["word"],
                  val["definition"],
                  val["kana"],
                  val["romaji"],
                  val["note"],
                  htmlContent,
                  key
                )); //html injecting
              }
            })
          );
        } //end for...in
      });
      $("#japanese").html(html); //changed from .text()

    } else {
      _results.push(
        _this.html(function(index, htmlContent) {
          if (
            _this
            .text()
            .toUpperCase()
            .indexOf(_term["word"].toUpperCase()) >= 0
          ) {
            return (html = define_replace(
              _term["word"],
              _term["definition"],
              _term["kana"],
              _term["romaji"],
              htmlContent
            ));
          }
        })
      );
    }
  }); //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);

  return html.replace(
    '<a  data-html="true"  data-toggle="popover" title="Popover - title" data-content="' + def + '>' + word + " " + '</a>', "gi"
  ); //html building - replace word + space with html

  (n - adv, n, ctr) time;
  hours;
  (P) < /span></span >
}; // end define_replace
//index.html
<div class="define">
  <p id="japanese">ね 、 毎日 動画 今日 も 頑張りましょう</p>
</div>

1 Ответ

2 голосов
/ 21 января 2020

включают popper.min.js до bootstrap. js или используйте bootstrap.bundle.min.js и Включите всплывающие окна везде

$(function () {
  $('[data-toggle="popover"]').popover()
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...