简体   繁体   中英

Stop hover and click on element with not specific class attribute

I want to disable the hover (and click) on elements which do not have a specific class name attribute:

<svg>
   <path class="myClass"></path>
   <path class="myClass active"></path>
</svg>

Basically if path has not attribute className "active" don't hover or click

Tried:

    if (!$("path").hasClass("active")) {
        $(this).unbind('mouseenter mouseleave');
    };

But I believe I should use .attr("class"..) since it is a svg path

You can add event handler only to element has .active class. But if you can't do it, use :not() selector to select element hasn't .active class.

$("path:not(.active)").unbind('mouseenter mouseleave')

This demo uses the .attr() function. with this you will have to loop through each desired element and loop its class list (if exist) and see if it contains the .active class if not then unbind the events of that element.

 $('p').on('mouseenter', function() { $(this).css('background', 'blue'); }) $('p').on('mouseleave', function() { $(this).css('background', 'black'); }) $('p').each(function(indx, elem) { var activeNotFound = 1; var classes = []; if ($(elem).attr('class') !== undefined) { // check if elem has attribute class classes = $(elem).attr('class').split(" "); // split into array the attribute class $.each(classes, function(ndx, classname) { // loop each class to check if active exist if (classname === 'active') { activeNotFound = 0; } // removed the else part. }); } if (activeNotFound) { // if no active class found unbind events $(elem).unbind('mouseenter mouseleave') } }) 
 div p { width: 100px; height: 100px; background: #000; border: 5px solid #000; } p.active { border: 5px solid red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h4>Note: I used a different element for this demo. Just change it to the needed elements and also update the script</h4> <div> <p class="myClass"></p> <p class="myClass active"></p> <p></p> </div> 

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