使用Javascript/Jquery将单词替换为图像

Replacing word(s) with image using Javascript/Jquery

本文关键字:替换 图像 单词 Javascript Jquery 使用      更新时间:2023-09-26

我有这个:

$(".forum-threadview-post-text:contains(':P')").html(":P").replaceWith("<img src='http://website.com/images/emotes/tongue.png' />");

它应该取":p"的任何实例,并将其替换为表情符号图像。但是,它使用:P来获取帖子,并用该图像替换整个帖子。如何仅替换:P。

尝试

var tImg = "<img src='http://website.com/images/emotes/tongue.png' />";
$(".forum-threadview-post-text:contains(':P')").html(function (_, html) {
     return html.replace(/:P/g , tImg )
});

演示

您的元素不能按预期工作的原因是,您正在用图像替换匹配的元素,而不是它的特定内容。您可以使用.html(函数(index,oldhtml))来获取每个元素的html并替换它。

或者:

$(".forum-threadview-post-text:contains(':P')").contents().each(function () {
    if(this.nodeType === 3 && /:P/g.test(this.nodeValue)) {
       $(this).parent().html(this.nodeValue.replace(/:P/g,"<img src='http://placehold.it/10x10' />"));
    }
});

我认为最好不要假设文本将是传入选择器的直接子级。我还认为,假设您正在搜索的文本不能出现在子代HTML标记中有点冒险。迄今为止给出的所有其他答案都至少在其中一个领域存在问题。

此外,更好的做法是使代码可重用。以下易于重用的函数将完全满足您的需要,不会被零散的HTML标记属性搞砸,并且可以工作!

function descendantContents($el, textToFind) { // this could be made a jQuery plugin
   var result = $el
      .find(':not(script)')
      .contents()
      .filter(function () {
         return this.nodeType === 3 && $(this).text().indexOf(textToFind) !== -1;
      });
   return result;
}
function replaceText(scopeSelector, textToFind, replacementHtml) {
   descendantContents($(scopeSelector), textToFind)
      .each(function () {
         var element = $(this);
         var parts = element.text().split(textToFind);
         element.before(document.createTextNode(parts[0]));
         for (var i = 1, l = parts.length; i < l; i += 1) {
            element.before(replacementHtml);
            element.before(document.createTextNode(parts[i]));
         }
         element.remove();
      });
};

这些功能已经在Firefox 25.0.1、Chrome 30.0.1599.101 m和10.0.9206.1721中使用jQuery 1.6.1进行了测试(我知道,这是一个旧版本,但应该会让你感觉更好,而不是更糟)。

对于任何希望做得更好的人,请尝试使用以下HTML:代码

<div>
   <div>will this <span title="alt:Private">really</span> work :P</div>
</div>