How do I use JQuery to select a whole <li> tag and make it a link?

断了今生、忘了曾经 提交于 2019-12-05 18:02:22
Konstantin Tarkus
// when the page is loaded..
$(function() {
    // make the cursor over <li> element to be a pointer instead of default
    $('li.clickable').css('cursor', 'pointer')
    // iterate through all <li> elements with CSS class = "clickable"
    // and bind onclick event to each of them
    .click(function() {
        // when user clicks this <li> element, redirect it to the page
        // to where the fist child <a> element points
        window.location = $('a', this).attr('href');
        return false;
    });
});

BTW, you can implement the same functionality with HTML/CSS only (without JavaScript). But this is another question.

For a less jQuery centric approach.

If you were to wrap the contents of the li within the <a> and display: block on a, you'd get the whole li clickable.

edit - Using headings in the <a> won't validate, but there's no reason not to swap the h tags out for <p> or similar and apply styles to them.

<style type="text/css">
.clickable a
{
     display: block;
}
</style>

<li class="alt clickable">
     <a href="/dave.htm">
     <h4>Fusce porta varius eros</h4>
     <h5>22 Feb 2009</h5>
     <p>Donec bibendum, mauris at vulputate vestibulum, nulla odio eleifend sem, in adipiscing orci neque sit amet ipsum.</p>
     </a>
</li>

$(li).text.append(""+[Link.n]+"")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!