最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Adding Click event for Array Elements in javascript - Stack Overflow

programmeradmin1浏览0评论

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]
]

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]
]
Share Improve this question edited Sep 1, 2013 at 17:23 putvande 15.2k3 gold badges36 silver badges51 bronze badges asked Apr 1, 2013 at 7:47 Arul AnthonyArul Anthony 231 gold badge1 silver badge4 bronze badges 1
  • Are you sure that array should'nt contain strings? If so -> $( newItems.join(', ') ).click() ? – adeneo Commented Apr 1, 2013 at 7:53
Add a ment  | 

4 Answers 4

Reset to default 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/ymuHR/

Variant #2*. Flatten array and convert into jQuery collection:

$([].concat.apply([], newItems)).click(function() {
    alert(this.id);
});

Demo: http://jsfiddle/ymuHR/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

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

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'
        });
    });
}
发布评论

评论列表(0)

  1. 暂无评论