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

后端 未结 4 1771
臣服心动
臣服心动 2020-12-03 10:49

This is a simplified version of my problem.

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



        
相关标签:
4条回答
  • 2020-12-03 11:22

    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!

    0 讨论(0)
  • 2020-12-03 11:26

    To wrap the element

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

    And to unwrap

    $(".onoff").parent().replaceWith($(".onoff"));
    
    0 讨论(0)
  • 2020-12-03 11:26

    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.

    0 讨论(0)
  • 2020-12-03 11:30

    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 讨论(0)
提交回复
热议问题