3

我正在尝试使用 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

这是一个聊天应用程序,我正在搞乱并且我相当新,所以如果你可以在你的代码中包含一些解释,那将有帮助:)

4

2 回答 2

5

可能看起来像(使用 jQuery):

$('div#log').find('p').html(function( html ) {
    return html.replace(':)', '<img src="happy.png"/>');
});

显然,这应该变得更复杂一些。我可以想象一个查找对象,您可以在其中将字符串链接到图像,例如:

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;
});
于 2011-07-04T12:33:20.667 回答
0

你试过这样做吗?

<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/

于 2011-07-04T12:36:10.157 回答