Pradeep
Pradeep

Reputation: 6603

dynamic selector for onClick not working

I want to make simple onClick event

$('._1').click(function(){
        window.open('abc.html?parameter=1');
    });

in above case , i have _1 as a class, now there are multiple such elements, and 1 here also acts as parameter to window.open request

but there are multiple click events i want to bind

var arrayOfValues = [1,2,4,6,7,8];
for(var z=0;z<arrayOfValues.length;z++)
    $('._'+arrayOfValues[z]+'').click(function(){
        window.open('abc.html?parameter='+arrayOfValues[z]);
    });

but this is not working

Upvotes: 1

Views: 184

Answers (1)

thecodeparadox
thecodeparadox

Reputation: 87073

var arrayOfValues = [1,2,4,6,7,8];

$.each(arrayOfValues, function(key, val) {

   for(var z=0;z<arrayOfValues.length;z++) {
     $( '._'+arrayOfValues[z] ).click(function(){
                             ^ -- dont need quote here
       window.open('abc.html?parameter='+arrayOfValues[z]);

     });
   }

   // jQuery loop
   $( '._' + val ).click(function(){

        window.open('abc.html?parameter='+arrayOfValues[z]);

    });

});

But if you elements are added to document after page load then you should try with delegate event handler .on().

var arrayOfValues = [1,2,4,6,7,8];

$.each(arrayOfValues, function(key, val) {

    $('body').on('click', '._'+ arrayOfValues[z], function(){

        window.open('abc.html?parameter='+arrayOfValues[z]);

    });

});

Upvotes: 2

Related Questions