1

I want to make the whole staff-container linked to the first href inside of it. (The one in staff-picture). How do I write this with jQuery? I'm pretty confused with attr() and I know that I have to use it.

In the following HTML, the jQuery should make staff-container linked to 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>

EDIT: Thanks to the answers I used this jQuery:

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

If there is no link inside staff-picture I do NOT want it to link the email. If jQuery can't find the link in staff-picture, I want the click to do nothing.

4

3 回答 3

3

Try like this

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

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

like this..??If you want specifically first anchor tag then you can give like

window.location.href = $(this).find('a').eq(0).attr('href');
于 2013-05-10T12:48:03.907 回答
1

Try this:

$('.staff-container').click(function() {
    var $first_link = $(this).find('a').first();
    window.location.href = $first_link.attr('href');
});
于 2013-05-10T12:49:07.643 回答
1

Pure JS version: should be a bit faster than 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@wcskids.net">email@wcskids.net</a></p>
    </div>
</div>

Working tested

于 2013-05-10T13:10:24.350 回答