开发者

JavaScript to change links on page?

I'm pretty new to JavaScript and am wondering ho开发者_C百科w on a page with links to images, i.e. http://www.example.com/image.jpg I can get them to be changed automatically by JavaScript to be embedded, ie with <img> tag

Hope that makes sense!

Thanks


We're particularly fond of the jQuery framework here, as it makes this sort of task very easy. With jQuery on your page, you can easily do this:

$(document).ready(function() {
    $('a[href$=.jpg]').each(function() {
        var imageSrc = $(this).attr('href');
        var img = $('<img />').attr('src', imageSrc);

        $(this).replaceWith(img);
    });
});

This will work specifically for <a> tags whose href attributes end with .jpg You can expand it to other file extensions, of course, but to dynamically determine whether a link leads to an image if the URL is not obvious would be a far greater challenge.


Do you mean convert all image url's to hyperlinks "pointing" to the images?

var x = document.getElementById('body');
x.innerHTML = x.innerHTML.replace(/(http:\/\/[^ ]+)/g,'<a
href="$1">$1</a>/');

I haven't tested this, but it should work. No third-party frameworks are needed.

From here

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜