[英]Find and delete text, then insert an image with jquery or javascript
我正在嘗試使用 jquery 或 javascript 將文本替換為圖像。 例如
<div id="log">
<p>this is a :) happy face</p>
<p>this is a :( sad face</p>
<p>these are :/ x( :P other faces</p>
</div>
我嘗試了一些事情,但要么我最終替換了整個字符串,要么瀏覽器不渲染圖像而是顯示 html
this is a <img src="happy.png"> face
這是一個聊天應用程序,我正在搞亂並且我相當新,所以如果你可以在你的代碼中包含一些解釋,那將有幫助:)
可能看起來像(使用 jQuery):
$('div#log').find('p').html(function( html ) {
return html.replace(':)', '<img src="happy.png"/>');
});
顯然,這應該變得更復雜一些。 我可以想象一個查找 object ,您可以在其中將字符串鏈接到圖像,例如:
var myMap = {
'\\:\\)': 'happy.png', // need to escape those for regex
'\\:\\(': 'sad.png',
'\\:\\/': 'other.png'
};
$('div#log').find('p').html(function( _, html ) {
for(var face in myMap) {
html = html.replace( new RegExp( face, 'g' ), '<img src="' + myMap[ face ] + '"/>' );
}
return html;
});
你試過這樣做嗎?
<div id="log">
<p id='my'>this is a :) happy face</p>
<p>this is a :( sad face</p>
<p>these are :/ x( :P other faces</p>
</div>
var p = $('#my').html();
var r = p.replace(':)', '<img src="happy.jpg">');
$('#my').html(r);
在這里小提琴: http://jsfiddle.net/PuDMx/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.