Adding Click event for Array Elements in javascript
17,159
Solution 1
Try this ...Let your newItems is the MultiDimensional variable of element "li"
for(var i=0;i<newItems.length;i++)
{
for(var j=0;j<newItems[i].length;j++)
{
newItems[i][j].addEventListener('click',function(){
// Your On Click code
},false);
}
}
Solution 2
Assuming that newItems
contains arrays of Nodes, not strings.
Variant #1. Simple for loop
:
for (var i = newItems.length; i--;) for (var j = newItems[i].length; j--;)
$(newItems[i][j]).click(function() {
// click
});
Demo: http://jsfiddle.net/ymuHR/
Variant #2*. Flatten array and convert into jQuery collection:
$([].concat.apply([], newItems)).click(function() {
alert(this.id);
});
Demo: http://jsfiddle.net/ymuHR/1/
Solution 3
Or you can use map function of jquery
$.map( newItems , function( val, i ) {
$('#'+val).click(function(){
//do something.
});
});
I know its late. but it is new late for improvements. Regards
Author by
Arul Anthony
Updated on June 05, 2022Comments
-
Arul Anthony almost 2 years
I am new to javascript I have a multi dimensional array which has 'li' in it. i want to add click event listener for all the li in my multidimensional array my array is like this
newItems = [ [li.pL14, li, li.pR15], [li.pL14, li, li.pR15], [li.pL14, li, li.pL14], [li, li.pR15, li.description], [li.pL14, li, li.pR15], [li.pL14, li] ]