Я использую элементы .each () для pu sh / inject html, чтобы динамически создавать popover (для определений словаря). Однако я замечаю, что если одно и то же слово повторяется в предложении, элементы не вставляются после первого вхождения.
Вот мой код:
(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()
$(function () {
$('[data-toggle="popover"]').popover()
})
HTML
<p class="define">毎日 今日 も 今日 頑張りましょう </p>
Вот ссылка codepen на код в действии. Как видите, повторяющееся слово в середине не активируется, и в консоли к нему не добавляется разметка.