Coffeescript: how to link div, but override link if child links are clicked

為{幸葍}努か 提交于 2019-12-25 04:58:15

问题


I find it hard to explain, so please request more info if you need it.

I have a div like so:

<div id="clickable">
  <p>Some content</p>
  <a href="google.com" class="link">Google</a>
  <a href="yahoo.com">Yahoo</a>
</div>

I want the div to be clickable, and link to the href of an attribute with class 'link'. This part I have done:

  $('#clickable').on 'click', (ev) ->
    window.location = $(this).find('.link').attr('href')
    return false

But, what should happen is if a user clicks a link within the div, that links location takes precedence. So, in the above example, if you click yahoo it will direct to yahoo. At the moment, it forces google.


回答1:


The call to update window.location and subsequent return false (stopping the click's propagation) is happening regardless of the normal behaviour of a link.

Try this:

$('#clickable').on('click', (ev) ->
  unless $(ev.target).is('a')
    window.location = $('.link', @).attr('href') 
    false
)



回答2:


This is because of event bubbling. Click on a bubbles to div and a click handler fires on div which redirects you to .link. Since the JavaScript is single-threaded, then the top handler is fired as the last one and you are always redirected to .link.

Try adding this code:

$('#clickable').on 'click', 'a', (ev) ->
    ev.stopPropagation()

Don't forget about 'a' part, which filters click to a elements. You can use jQuery's filters there.

EDIT

Since for unknown reasons the snippet I posted is not working for you, then how about this? (this time replace the code)

$('#clickable').on 'click', (ev) ->
    if ev.target.href
        window.location = ev.target.href
        return
    window.location = $(this).find('.link').attr('href')
    return false


来源:https://stackoverflow.com/questions/11223626/coffeescript-how-to-link-div-but-override-link-if-child-links-are-clicked

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