Prevent default on link if parent hasClass()

一世执手 提交于 2019-12-25 08:09:07

问题


Simplified HTML:

<ul>
    <li class="no-link"><a>Should not be clickable</a>
        <ul>
            <li><a>Should be clickable</a></li>
            <li><a>Should be clickable</a></li>
        </ul>
    </li>
</ul>

Javascript:

jQuery(document).ready(function( $ ) {

    $('a').parent().click(function(e) {
        if($(this).hasClass('no-link')){
            e.preventDefault();
        }
    });
})

Works fine on the link that should not be clickable, but also affects the two descendant a tags. Why? I thought parent() only traversed up a single step in the DOM.

I'm adding the class programatically via WordPress (as an option in the Appearance > Menus control panel), so targeting the a tag directly via class is not really an option.


回答1:


What you want is to actually capture the click on a element and then check for parent class inside it.

Just change your code to:

$('a').click(function(e) {
     if($(this).parent().hasClass('no-link')){
         e.preventDefault();
     }
});



回答2:


    $('li > a').click(function(e) {
        if($(this).parent().hasClass('no-link')){
            console.log('parent has class no-link')
            e.preventDefault()
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li class="no-link"><a href="#">Should not be clickable</a>
        <ul>
            <li><a href="#">Should be clickable</a></li>
            <li><a href="#">Should be clickable</a></li>
        </ul>
    </li>
</ul>



回答3:


"I thought parent() only traversed up a single step in the DOM."

It does. But you are attaching your click handler to the parent, and click events bubble up from the clicked item through their parent, the parent's parent, etc., and can be cancelled anywhere along that chain. So your code cancel all clicks for all anchors within that parent element.

Try this instead:

$('a').click(function(e) {
   if($(this).parent().hasClass('no-link')){
     e.preventDefault();
   }
});

That is, handle the click event at the anchor level, testing the parent of the clicked item.




回答4:


Simple solution is the best - just stop propagation:

jQuery(document).ready(function( $ ) {
    $('a').parent().click(function(e) {
        e.stopPropagation(); // Preventing from event bubbling and capturing
        if($(this).hasClass('no-link')){
            e.preventDefault();
        }
    });
})


来源:https://stackoverflow.com/questions/38906958/prevent-default-on-link-if-parent-hasclass

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