我正在修改jQuery highlight plugin。除了title
之外,我想提供一个element: 'abbr'
参数。
以下是插件的摘录:
jQuery.extend({
highlight: function (node, re, nodeName, className, titleVal) {
if (node.nodeType === 3) {
var match = node.data.match(re);
if (match) {
console.log('Title after: ' + titleVal);
var highlight = document.createElement(nodeName || 'span');
highlight.className = className || 'highlight';
highlight.setAttribute('title', titleVal);
var wordNode = node.splitText(match.index);
wordNode.splitText(match[0].length);
var wordClone = wordNode.cloneNode(true);
highlight.appendChild(wordClone);
wordNode.parentNode.replaceChild(highlight, wordNode);
return 1; //skip added node in parent
}
} else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
!/(script|style)/i.test(node.tagName) && // ignore script and style nodes
!(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
for (var i = 0; i < node.childNodes.length; i++) {
i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
}
}
return 0;
}
});
jQuery.fn.unhighlight = function (options) {
var settings = { className: 'highlight', element: 'span' };
jQuery.extend(settings, options);
return this.find(settings.element + "." + settings.className).each(function () {
var parent = this.parentNode;
parent.replaceChild(this.firstChild, this);
parent.normalize();
}).end();
};
jQuery.fn.highlight = function (words, options) {
var settings = { className: 'highlight', element: 'span', titleVal: 'Default', caseSensitive: false, wordsOnly: false };
jQuery.extend(settings, options);
console.log('Title passed:' + settings.titleVal);
if (words.constructor === String) {
words = [words];
}
words = jQuery.grep(words, function(word, i){
return word != '';
});
words = jQuery.map(words, function(word, i) {
return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
});
if (words.length == 0) { return this; };
var flag = settings.caseSensitive ? "" : "i";
var pattern = "(" + words.join("|") + ")";
if (settings.wordsOnly) {
pattern = "\\b" + pattern + "\\b";
}
var re = new RegExp(pattern, flag);
return this.each(function () {
console.log('Title before: ' + settings.titleVal);
jQuery.highlight(this, re, settings.element, settings.className, settings.titleVal);
});
};
abbr { text-decoration: underline; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>These are a collection of words for an example. Kthx.</p>
<button onclick="$('p').highlight('collection', {element: 'abbr', titleVal: 'A group of things or people'})">What's "collection"?</button>
看看控制台。请注意,标题已成功传递,在调用插件函数之前定义,然后在其中未定义。我很确定它很简单,但我没有看到它。
答案 0 :(得分:2)
更改for
循环中的该行
i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
到
i += jQuery.highlight(node.childNodes[i], re, nodeName, className, titleVal);
修复它。