简体   繁体   中英

Bind click function of child href to parent div

<div class="parent">
   <a href="#">download link</a>
</div>


$(".parent").bind("click", function(){

alert('test');

});

would like to bind the href click function so that when the .parent is clicked it goes to the location of the nested link.

$(".parent").bind("click", function(){
    window.location.href = $(".parent a").attr("href");
});

Try this:

$(".parent").bind("click", function(){
    alert($(this).children('a').attr('href'));
});​

Since you have only one link inside a parent element, you can totally avoid javascript if your link fills entirely the parent width and height: just set this CSS

.parent a {
   display: block;
   width  : 100%;  /* or set in px if parent has not width specified */
   height : 100%;  /* or set in px if parent has not height specified */
}

Try something like the following, it should work:

$(".parent a").bind("click", function(){
    alert('test');    
});

Then you can do something like that :

// Choose the a tag specifically
$(".parent").bind("click", function() {
    alert($(this).find('a').attr('href'));
});

That should do the trick

Good luck!

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