javascript jquery用图像替换文本,帮助
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5972119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery replace text with image, help
提问by ben
("*").each(function () {
if ($(this).children().length == 0) {
$(this).text($(this).text().replace('basketball','test'));
}
});
i'm only able to change the text to another string of text, but how can I pass an image?
我只能将文本更改为另一个文本字符串,但如何传递图像?
回答by Vivin Paliath
("*").each(function () {
if ($(this).children().length == 0) {
var newHTML = $(this).html().replace('basketball','<img src = "image.jpg" />');
$(this).html(newHTML);
}
});
EDIT
编辑
My mistake. I thought you wanted to replace the entire element. Check out my updated answer.
我的错。我以为你想替换整个元素。查看我更新的答案。
回答by SLaks
You need to modify the html()
rather than the text()
.
您需要修改html()
而不是text()
。
You can simplify your code to
您可以将代码简化为
$("*").filter(function() { return !$(this).children().length; })
.html(function(index, old) { return old.replace('basketball', '<img ... />'); });
回答by ricick
I'd reccomend JQIRfor this. first replace "basketball"
with "<span class="jqir">basketball</span>"
as you are doing above. Then run the following:
为此,我建议使用JQIR。先更换"basketball"
与"<span class="jqir">basketball</span>"
你在上面干什么。然后运行以下命令:
$(".jqir").jQIR("png", "images/");
This assumes that you have an image images/basketball.png. You can adjust as needed.
这假设您有一个图像 images/basketball.png。您可以根据需要进行调整。