开发者

How to replace character with image using jQuery?

How to replace ALL * characters in some list?

Example:

<div class="nav开发者_JAVA百科">
        <ul>
            <li><a href="#">Hotels *****</a></li>
            <li><a href="#">Hotels ****</a></li>
            <li><a href="#">Hotels ***</a></li>
            <li><a href="#">Some other menu</a></li>
        </ul>
</div>

jQuery example:

$().ready(function () {
    if ($('.logo')[0].offsetWidth == 295) {
        $('.nav ul li a span').each(function () {
            string = $(this).text();
            $(this).html('<img src="img/star.png" alt="' + string + '" />');
        });
    }
});

I want to change ALL the stars, not just one (with this code, all works like it should, except it changes all stars with one image). it shuld be how many star char's, that many images.

The goal is to change it like this:

some text ***** 

with

some text <img src="img/star.png" alt="star" /><img src="img/star.png" alt="' + string + '" /><img src="img/star.png" alt="' + string + '" /><img src="img/star.png" alt="' + string + '" /><img src="img/star.png" alt="' + string + '" />


Iterate over the required elements and use a regex to change the '*' to the <img> elements. You will need a /g flag on the regex to change all of them in the string.

$('...').each(function() {
    var $this = $(this),
        html = $this.html();

    html = html.replace(/\*/g, '<img href="...">');
    $this.html(html);
});


Your selector is not in sync with your markup:

$('.nav ul li a span') -> there is no span in your lis

Fixing that selector, here's the code that would do the trick:

$('.nav ul li a').each(function() {
    var txt = $(this).text();
    var img = '<img src="img/star.png" alt="' + txt + '" />'
    var html = txt.replace(/\*/g, img);  // replace every star with an image tag
    $(this).html(html);
});

Here's demo: http://jsfiddle.net/mrchief/kycae/


You can do this very cleanly by just passing a function to the html()[docs] method.

$('.nav ul li a').html(function(i,html) {
    return html.replace(/\*/g, '<img src="http://dummyimage.com/30x30/f00/fff.png&text=*" alt="' + html + '" />');
});

Example: http://jsfiddle.net/vrqgv/


Once you have your string:

some text ***** 

you can use split() and join() to replace the stars with the images:

var original = 'some text *****' ;
var withImages = original.split('*').join('<img src="img/star.png" alt="star" />');

Split creates an array with each element separated by the string passed in, and join returns an array to a string, inserting the passed string between each element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜