【问题标题】:Find and replace text without destroying click events在不破坏点击事件的情况下查找和替换文本
【发布时间】:2014-08-21 17:51:08
【问题描述】:

客户要求以特定方式设计其网站上的所有商标符号(™ 和 ®);考虑到它们出现的数量——从标题到正文和导航——我们决定用 JavaScript 来做这件事。

我们要做的是在页面文本中找到 ™ 和 ® 的每个实例(但不在元素属性内),并将它们包装在 <sup> 标签中,以便我们可以在 CSS 中设置它们的样式。

这是我们目前拥有的代码:

Trademark = {
    init: function () {
        $('body').contents().each(function () {
            var element = $(this);
            if (element.html()) {
                element.html(element.html().replace(/(?![^<]+>)™/gi, '<sup class="trademark">™</sup>'));
                element.html(element.html().replace(/(?![^<]+>)®/gi, '<sup class="trademark">®</sup>'));
            }
        });
    }
}

$(function () {
    Trademark.init();
})

它工作得很好,但是我们现在遇到的问题是 JavaScript 点击事件没有被注册到内容被替换的元素上——我假设是因为当它们被从 DOM 中删除时被操纵。

是否对此进行了修改(对 JS 或正则表达式)可以阻止这种情况的发生?谢谢!

【问题讨论】:

标签: javascript jquery regex replace find


【解决方案1】:

仅过滤 textNodes 并替换 parentNode 的 innerHTML,这样元素本身就不会被替换并且事件处理程序应该保持不变。

Trademark = {
    init: function () {
        $('*').contents().each(function() {
            if (this.nodeType == 3 && this.nodeValue) {
                if ( this.nodeValue.indexOf('™') != -1 || this.nodeValue.indexOf('®') != -1 ) {
                    this.parentNode.innerHTML = this.parentNode.innerHTML.replace(/(?![^<]+>)(™|®)/gi, '<sup class="trademark">$1</sup>');
                }
            }
        });
    }
}

FIDDLE

【讨论】:

    猜你喜欢
    • 2022-11-01
    • 2017-09-14
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多