2

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]
]
1
  • Are you sure that array should'nt contain strings? If so -> $( newItems.join(', ') ).click() ?
    – adeneo
    Commented Apr 1, 2013 at 7:53

4 Answers 4

3

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/

0
1

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

0

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);
  }
}
0

HTML

<div id="abc1"><a href="#">linl 01</a></div>
<div id="abc2"><a href="#">linl 02</a></div>
<div id="abc3"><a href="#">linl 02</a></div>
<div id="abc4"><a href="#">linl 02</a></div>

jQuery

var ids = ["#abc1", "#abc2", "#abc3", "#abc4"];
for(var i=0;i<ids.length;i++) {
    $(ids[i]).click(function(){
        $(this).find("a").css({
            'font-weight':'bold'
        });
    });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.