JsFiddle working demo
Use the .each() method to scroll .each() your elements, and check the flag for event handlers already using .data() , if true , skip the current loop. Otherwise, attach an event handler to the element and set the flag to true .
function attachClickToElem() { $('.elem').each(function () { var $elem = $(this); // check if event handler already exists // if exists, skip this item and go to next item if ($elem.data('click-init')) { return true; } // flag item to prevent attaching handler again $elem.data('click-init', true); $elem.on('click', function () { alert('Hello World'); }); }); }
Literature:
user1823761
source share