[英]Adding data to highlighted text in JQuery and Javascript
I found this excellent code online for highlighting words in text by wrapping then with <SPAN>
tags and a user defined class. 我在网上找到了这个出色的代码,该代码通过用
<SPAN>
标记和用户定义的类进行包装,然后突出显示文本中的单词。 I use this a few times over for highlighting multiple searches at once without any problems. 我多次使用它来一次突出显示多个搜索而没有任何问题。
What I want to do is add an extra feature to this code to add more data to each of the tags added using JQuery's .data() method. 我想做的是在此代码中添加一个额外的功能,以向使用JQuery的.data()方法添加的每个标签添加更多数据。 But the function is so tidy and efficient I cant find where I need to inject it!
但是功能是如此整洁和高效,我无法找到需要注入的位置!
I want a function like highlightJQueryText(elem, str, className, dataName, data)
我想要像
highlightJQueryText(elem, str, className, dataName, data)
这样的函数
highlightJQueryText: function (elem, str, className) {
var regex = new RegExp(str, "gi");
return elem.each(function () {
$(this).contents().filter(function() {
return this.nodeType == 3 && regex.test(this.nodeValue);
}).replaceWith(function() {
return (this.nodeValue || "").replace(regex, function(match) {
return "<span class=\"" + className + "\">" + match + "</span>";
});
});
});
}
PS. PS。 it should add a
span.data("dataName", data)
only to those tags created at the same time. 它应该仅将
span.data("dataName", data)
到同时创建的那些标签中。 (Not everything in the container with the class "className".) Because I run the function on the same container multiple times for different phrases using the same "ClassName", but still want a different set of data stored on each phrase. (不是容器中具有“ className”类的所有内容。)因为我在同一容器上针对使用相同“ ClassName”的不同短语多次运行该函数,但是仍然希望在每个短语上存储一组不同的数据。
Something like this should do the trick : 这样的事情应该可以解决问题:
highlightJQueryText: function (elem, str, className, dataName, data) {
var regex = new RegExp(str, "gi");
return elem.each(function () {
$(this).contents().filter(function() {
return this.nodeType == 3 && regex.test(this.nodeValue);
}).replaceWith(function() {
return (this.nodeValue || "").replace(regex, function(match) {
return "<span data-"+dataName+"=\""+data+"\" \
class=\""+className+"\">"+match+"</span>";
});
});
});
}
or if you really want to use the JQuery data
method : 或者如果您真的想使用JQuery
data
方法:
highlightJQueryText: function (elem, str, className, dataName, data) {
var regex = new RegExp(str, "gi");
return elem.each(function () {
$(this).contents().filter(function() {
return this.nodeType == 3 && regex.test(this.nodeValue);
}).replaceWith(function() {
return (this.nodeValue || "").replace(regex, function(match) {
return $("<span class=\""+className+"\">"+match+"</span>")
.data(dataName, data);
});
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.