使用Javascript/Jquery将单词替换为图像
Replacing word(s) with image using Javascript/Jquery
我有这个:
$(".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>
相关文章:
- 用Javascript替换图像和图像标题/alt文本
- 用 jquery 替换图像和类
- 用于多次替换图像的 Jquery 按钮
- JavaScript/PHP 从数据库动态替换图像源
- 单击时切换和替换图像
- 重新加载/替换图像 jQuery 作为
- 中的列表项
- 快速替换图像 src 时 Firefox 中的内存使用情况
- 用不同的图像/按钮替换图像 - javascript
- 检测网址/链接,并用 img 标签替换图像,用 href 替换链接
- 使用Kinetic.js html5画布替换图像上的文本
- 用javascript替换图像上的src
- 用jquery替换图像文件名
- 用Aviary/Creave SDK图像编辑器替换图像
- 在CLick上替换图像SRC
- jquery按时间间隔替换图像
- 用jQuery替换图像
- 在点击时用视频替换图像
- 在使用图像的地方替换图像- Javascript
- 在表格单元格内替换图像不起作用
- 一个错误事件添加一个新类并计算它替换图像源的次数