开发者

jQuery: Easiest way to wrap an image tag with an A anchor tag

This is a simplified version of my problem.

I have two buttons, and one image. The image code is something like this

<img class="onoff" src="image.jpg">

When I press button one I want the image to be wrapped in an A tag, like

<a href="link.html">
<img class="onoff" sr开发者_运维技巧c="image.jpg">
</a>

And when I press the other button, the A tags should be removed.

What's the easiest way of doing this with jQuery?


you have already many answers, but (at least before I started writing) none of them will correctly work.

They do not take into account that you should not wrap the <img> with multiple <a> tags. Furthermore, do not try to unwrap it if it is not wrapped! You would destroy your DOM.

This code simple does a verification before wrapping or unwrapping:

$(function(){
    var wrapped = false;
    var original = $(".onoff");

    $("#button1").click(function(){
        if (!wrapped) {
            wrapped = true;
            $(".onoff").wrap("<a href=\"link.html\"></a>");
        }
    });

    $("#button2").click(function(){
        if (wrapped) {
            wrapped = false;
            $(".onoff").parent().replaceWith(original);
        }
    });
});

Good luck!


To wrap the element

$(".onoff").wrap("<a href='link.html'></a>");

And to unwrap

$(".onoff").parent().replaceWith($(".onoff"));


Try something like this:

$("img.onoff").wrap(
    $("<a/>").attr("href", "link.html"));

But perhaps using jQuery's click binding on the image itself would be better than wrapping the image in an anchor.


you can use jQuery wrap() function.

The code is:

    <input type="button" id="button1" value="Wrap" />
    <input type="button" id="button2" value="Unwrap" />
    <img class="onoff" src="image.jpg" alt="" />

    $(function() {
        //wrap
        $('#button1').click(function() {
            $('.onoff').wrap('<a href="link.html"></a>');
            //if you want to make sure multiple clicks won't add new <a> around it
            //you could unbind this event like that:
            //$(this).unbind( "click" )
        });
        //unwrap
        $('#button2').click(function() {
            $('.onoff').parent().each(function() { $(this.childNodes).insertBefore(this); }).remove();
           //$(this).unbind( "click" )
        });
    });  
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜