how to stop redirection of parent href tag when clicked on child div?

拟墨画扇 提交于 2020-01-03 15:55:47

问题


i have the following structure

Code

 <a href="blah.html" class="re-direct">
    <div class="1div"></div>
    <div class="2div">
       <div class="click" data-id="text">click</div>
    </div>
 </a>
 <script>
  $(document).on('click',".click",function(){ alert($(this).data('id')) })
 </script>

the above code works fine but it redirects to the page blah.html how do i stop it from redirecting ?


回答1:


You need to stop the propagation of the click event up the DOM to the a element, and also prevent the default behaviour of the link:

$(document).on('click', ".click", function(e) { 
    e.stopPropagation();
    e.preventDefault();
    alert($(this).data('id')) 
});

Example fiddle



来源:https://stackoverflow.com/questions/24726358/how-to-stop-redirection-of-parent-href-tag-when-clicked-on-child-div

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