2013-05-10 67 views
1

我想让整个staff-container链接到里面的第一个href。 (staff-picture中的那个)。我如何使用jQuery编写此代码?我很困惑与attr(),我知道我必须使用它。将div链接到里面的href

在以下HTML中,jQuery应将staff-container链接到google.com。

<div class="staff-container"> 
    <div class="staff"> 
     <div class="staff-picture"> 
      <a href="http://www.google.com/"><img src="img/people/teachers/ahmed.png" /></a> 
     </div> 
     <p><span class="bold">Mr. Ahmed</span><br /> 
     Ext. 13417<br /> 
     Room 417/323<br /> 
     <a href="mailto:[email protected]">[email protected]</a></p> 
    </div> 
</div> 

编辑:谢谢你的答案,我用这个jQuery的:

$('.staff-container').click(function() { 
    window.location.href = $(this).find('a').attr('href'); 
}); 

如果里面有staff-picture没有任何联系,我不想它链接的电子邮件。如果jQuery无法在staff-picture中找到链接,我希望点击不做任何事情。

回答

3

尝试这样

$('.staff-container').click(function(e) { 

    if($(this).find('a').attr('href')) 
     window.location.href = $(this).find('a').attr('href');  
    e.preventDafault(); 
}); 

这样的.. ??如果你想明确的第一锚标记,那么你可以给喜欢

window.location.href = $(this).find('a').eq(0).attr('href'); 
+0

@Brett Merrifield对你有用。 – Gautam3164 2013-05-10 12:54:08

+0

我编辑我的答案..请考虑 – Gautam3164 2013-05-10 13:00:35

+0

它现在工作.. ?? – Gautam3164 2013-05-10 13:24:40

1

试试这个:

$('.staff-container').click(function() { 
    var $first_link = $(this).find('a').first(); 
    window.location.href = $first_link.attr('href'); 
}); 
1

纯JS版本:应该比jQuery快一点

<script> 
function link(loc){ 
    var href=loc.getElementsByTagName('a')[0].href; 
    console.log(this); 
    console.log(href); 
    loc.setAttribute("onclick","window.location.href='"+href+"'"); 
    loc.removeAttribute("onmouseover",""); 
} 
</script> 
<div class="staff-container" onmouseover="link(this)"> 
    <div class="staff"> 
     <div class="staff-picture"> 
      <a href="http://www.google.com/"><img src="img/people/teachers/ahmed.png" /></a> 
     </div> 
     <p><span class="bold">Mr. Ahmed</span><br /> 
     Ext. 13417<br /> 
     Room 417/323<br /> 
     <a href="mailto:[email protected]">[email protected]</a></p> 
    </div> 
</div> 

工作测试