【问题标题】:Bind click function of child href to parent div将子href的点击功能绑定到父div
【发布时间】:2012-03-30 09:55:56
【问题描述】:
<div class="parent">
   <a href="#">download link</a>
</div>


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

alert('test');

});

想绑定 href 点击功能,这样当点击 .parent 时,它会转到嵌套链接的位置。

【问题讨论】:

  • 给出完整的要求。其实你想做什么?

标签: javascript html jquery


【解决方案1】:
$(".parent").bind("click", function(){
    window.location.href = $(".parent a").attr("href");
});

【讨论】:

  • window.location.href = $(this).find('a').attr('href'); //这适用于不同的链接
【解决方案2】:

试试这个:

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

【讨论】:

    【解决方案3】:

    由于您在父元素中只有一个链接,如果您的链接完全填充父元素的宽度和高度,您可以完全避免使用 javascript:只需设置此 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 */
    }
    

    【讨论】:

    • 我会避免在 js 中这样做,除非在这种情况下我有一个有很多链接的轮播。感谢您的提示!
    【解决方案4】:

    然后你可以做这样的事情:

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

    这应该可以解决问题

    祝你好运!

    【讨论】:

    • amritpal 有一个更好的版本,因为children() 只浏览第一级儿童。 find() 浏览所有关卡,因此更贪心
    【解决方案5】:

    尝试以下方法,它应该可以工作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      相关资源
      最近更新 更多