简体   繁体   中英

Make DIV clickable with 2 or more links

I have some difficulties with jQuery. I need to ma div or section clickable (add link to block element) and I already implemented some code

$(document).ready(function() {
        $(".clickable").click(function(){
            window.location=$(this).find("a.slide-link").attr("href");
            return false;
        });
    });

But when the block has 2 or more links - links in this block don't work correctly. Always redirect to a.slide-link url.

How I can solve this issue? Thanks!

Update

<section class="clickable">
    <div>
        <div class="description">
            <ul>
                <li>Lorem ipsum</li>
                <li>Lorem ipsum</li>
                <li>Lorem ipsum</li>
                <li>Lorem ipsum <a href="http://url1.com">here</a></li>
            </ul>
        </div>
        <a class="slide-link" href="http://url2.com">URL2</a>
    </div>
</section>

Initial answer for initial question

In case of multiple match, $(this).find("a.slide-link") gives array of nodes, hence, .attr does not work.

If you want to redirect to the 1st link then update your code to

$($(this).find("a.slide-link")[0])

Updated answer for updated question

Your anchor within the section will not work because of event bubbling. For reference - http://www.w3schools.com/jsref/event_bubbles.asp

What you have to do is stop event to bubble. For that add this in your js

$(".clickable a").click(function(event){
     event.stopPropagation();
});

If it's just the links you want to work within the section, but not clicking the section itself, then you can use the following:

$(document).ready(function() {
    $(".clickable a.slide-link").click(function(){
        window.location=$(this).attr("href");
        return false;
    });
});

Though only if you're planning on doing something other than simply going to that address, in which case the above code is the same as having no code..

If you want the outer section to be a link itself, you'd be better using an <a> tag for that too, and setting it to display: block . You can't nest anchor tags within other anchor tags for obvious reasons.

I found answer

$(".clickable").click(function( event ) {
  var target = $( event.target );
  if ( !target.is( "a" ) ) {
    window.location=$(this).data("link");
  }
}

You can select an anchor by its href value $("a[href='www.myurl.com'")

Read more about the selectors here. javascript uses the same selectors as regular CSS. given the browser supports the selector. http://www.w3schools.com/cssref/css_selectors.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM