我想让整个 staff-container
链接到其中的第一个 href。 (staff-picture
中的那个)。我如何用 jQuery 编写这个?我对 attr()
很困惑,但我知道我必须使用它。
在下面的 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@wcskids.net">email@wcskids.net</a></p>
</div>
</div>
编辑:感谢我使用这个 jQuery 的答案:
$('.staff-container').click(function() {
window.location.href = $(this).find('a').attr('href');
});
如果 staff-picture
中没有链接,我不希望它链接电子邮件。如果 jQuery 在 staff-picture
中找不到链接,我希望点击不执行任何操作。
最佳答案
这样试试
$('.staff-container').click(function(e) {
if($(this).find('a').attr('href'))
window.location.href = $(this).find('a').attr('href');
e.preventDafault();
});
like this..??如果你想要特别的第一个 anchor 标签,那么你可以给 like
window.location.href = $(this).find('a').eq(0).attr('href');
关于javascript - 将 div 链接到其中的 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16482591/