دنبال کننده ها

۱۳۹۶ آبان ۱۱, پنجشنبه

jquery - Prevent .hover() to be bind more than once to the same element

[ad_1]



The title of this question reflects the final goal, which is preventing .hover() to be bind more than once to the same element.



Before asking I did a search on SO and I have found this question which is already answered: Checking if jQuery .hover action is already binded



Also I've Googled a lot about it and it looks like the accepted answer to that question is correct.



With that, I came up with a small piece of code which tries to do the following:



  1. Loop over all elements with a class class-name

  2. Obtain all the events on that element

  3. Check if the .hover() event is already bind on it

  4. If it's not, then add it.



$(document).ready(function() 
$('.class-name').each(function()
var events = $._data($(this)[0], 'events');

if ( !(events['mouseover'] && events['mouseout']) )
$(this).hover(
function() alert('IN'); ,
function() alert('OUT');
);

);
);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<a class="class-name">a</a>





The code above doesn't work and I cannot figure out where the error is. According to the JS console output, the events variable is undefined.



Any help appreciated. Thanks.




[ad_2]

لینک منبع