简体   繁体   中英

Make whole Div clickable using jQuery

CODE:

<style>
    .mydiv {
        border: 1px solid #00f;
        cursor: pointer; 
    }
</style>

<div class="mydiv">blah blah blah. 
    <a href="http://examples.com">Examples link</a>
</div>


I want to click on 'blah blah blah' text and jump to the ' http://examples.com ' link using jQuery.

JS:

$(".mydiv").click(function(){
    if($(this).find("a").length){
        window.location.href = $(this).find("a:first").attr("href");
    }
});

OR:

Simply write:

<a href="http://examples.com">
    <div class="mydiv">blah blah blah. 
        Examples link
    </div>
</a>

Move the anchor element out of the div to wrap it

<a href="http://examples.com">
    <div class="mydiv">blah blah blah</div>. 
    Examples link
</a>
$(document).on("click", ".mydiv", function(){
    location.href = "http://examples.com";
}

If you want to use jQuery to do this, you're looking for the click function.

$('.mydiv').click(function(){
    location.href = 'example.com';
}); 

you can simply do with HTML

<a href="http://examples.com">
   <div class="yourDiv">blah blah blah. 
      Examples link
   </div>
</a>

but

if you want to do that with jquery do something like this

$(document).ready(function(){

    $(".yourDiv").on('click', function(){
        //As an HTTP redirect (back button will not work )
        window.location.replace("http://www.example.com");
    });

});

With JQuery as was requested:

$(document).ready(function() {
  $('.mydiv').click(function() {
   document.location.href='http://examples.com';
  });
});

OFC, you can (and should) let the browser handle it as suggested by Hiral.

In consideration of the other answers which haven't yet been accepted, I assume that you want to use multiple <div class="mydiv"> , with differing href attributes of the <a> element.

If the <a> element will always be the last child of its parent:

$(".mydiv").click(function(){
    window.location.href = this.lastChild.href;
});

Remember to remove whitespace and the end of the <div> .

JSFiddle: http://jsfiddle.net/JAJuE/1/


If the <a> element will be somewhere (though not necessarily at the end) in the <div> :

HTML

<div class="mydiv">blah blah blah.
    <a href="http://examples.com" class="mylink">Examples link</a>
</div>

JS

$(".mydiv").click(function(){
    window.location.href = this.getElementsByClassName("mylink")[0].href;
});

JSFiddle: http://jsfiddle.net/JAJuE/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM