jQuery '.each' and attaching '.click' event jQuery '.each' and attaching '.click' event jquery jquery

jQuery '.each' and attaching '.click' event


One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.

For example:

HTML:

<body><div id="dog" class="selected" data-selected="false">dog</div><div id="cat" class="selected" data-selected="true">cat</div><div id="mouse" class="selected" data-selected="false">mouse</div><div class="dog"><img/></div><div class="cat"><img/></div><div class="mouse"><img/></div></body>

JS:

$( ".selected" ).each(function(index) {    $(this).on("click", function(){        // For the boolean value        var boolKey = $(this).data('selected');        // For the mammal value        var mammalKey = $(this).attr('id');     });});


No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {    ..    });

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.