【问题标题】:Adding data to highlighted text in JQuery and Javascript在 JQuery 和 Javascript 中向突出显示的文本添加数据
【发布时间】:2015-11-18 04:58:01
【问题描述】:

我在网上找到了这个出色的代码,用于通过使用<SPAN> 标记和用户定义的类包装来突出显示文本中的单词。我多次使用它来一次突出显示多个搜索,没有任何问题。

我想要做的是向这段代码添加一个额外的功能,以便为使用 JQuery 的 .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>";
                    });
                });
            });
        }

附言。它应该只为同时创建的标签添加span.data("dataName", data)。 (不是容器中具有“className”类的所有内容。)因为我使用相同的“ClassName”为不同的短语在同一个容器上多次运行该函数,但仍然希望在每个短语上存储一组不同的数据。

【问题讨论】:

  • 在 jsfiddle.net 中创建一个演示,其他人可以修改以帮助您解决问题

标签: javascript jquery highlight highlighting


【解决方案1】:

这样的事情应该可以解决问题:

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>";
            });
        });
    });
}

或者如果你真的想使用 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);
            });
        });
    });
}

【讨论】:

  • 感谢您的帮助,但第一种方法在深度 json 对象方面存在问题,第二种方法只是将文本替换为“[Object object]”
猜你喜欢
  • 2014-03-12
  • 1970-01-01
  • 2023-03-03
  • 2012-03-28
  • 1970-01-01
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 2011-12-25
相关资源
最近更新 更多