Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

each

I am not a programer but I enjoy building prototypes. All of my experience comes from actionScript2.

Here is my question. To simplify my code I would like to figure out how to attach '.click' events to div's that are already existing in the HTML body.

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

My (failed) strategy was:
1) make an array of objects:

var props = { "dog": "false", "cat": "true", "mouse": "false" };   

2) iterate through the array with '.each' and augment each existing div with a '.click' event. Lastly, construct a local variable.

here is a prototype:

$.each(props, function(key, value) {     $('#'+key+'-selected').click(function(){ var key = value;   }); }); 
like image 421
hcc Avatar asked Sep 23 '13 18:09

hcc


2 Answers

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');      }); }); 
like image 180
Neil.Allen Avatar answered Oct 07 '22 15:10

Neil.Allen


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.

like image 34
Oriol Avatar answered Oct 07 '22 15:10

Oriol