jQuery追加onclick函数

时间:2012-12-19 14:53:42

标签: javascript jquery

我一直坚持这个问题!基本上,我有这个数组:

var category = {
    id_1:[
          {id:"1_1", img:"img/prodotti-categorie/test.jpeg", titolo:"Name", prezzo:"8,50", link:""},
          {id:"1_2", img:"img/prodotti-categorie/test.jpeg", titolo:"Name", prezzo:"7,00", link:""},
          {id:"1_3", img:"img/prodotti-categorie/test.jpeg", titolo:"Name", prezzo:"7,00", link:""},
          {id:"1_4", img:"img/prodotti-categorie/test.jpeg", titolo:"Name", prezzo:"19,00", link:""},
          {id:"1_5", img:"img/prodotti-categorie/test.jpeg", titolo:"Name", prezzo:"10,00", link:""},
          {id:"1_6", img:"img/prodotti-categorie/test.jpeg", titolo:"Name", prezzo:"8,50", link:""},
          {id:"1_7", img:"img/prodotti-categorie/test.jpeg", titolo:"Name", prezzo:"12,00", link:""},
          {id:"1_8", img:"img/prodotti-categorie/test.jpeg", titolo:"Name", prezzo:"7.50", link:""}],
    id_2:[...

然后我得到这样的值:

for(var i=0, l=Object.keys(category["id_"+(cat_id)]).length; i<l; i++) {
        var img = category["id_"+(cat_id)][i]["img"];
        var title = category["id_"+(cat_id)][i]["titolo"];
        var price = category["id_"+(cat_id)][i]["prezzo"];

        $('#content').append('<div class="category-list item-'+ cat_id + '_' + i +'"><img src="' + img + '"><p>' + title +'</p><p>€' + price + '</p></div>');

       //From here begins my problem:
       //When i search fot the class added before and try to append or do anything else, variable i is always 8!
        $('.item-' + cat_id + '_' + i).click(function(){
             app.renderPageProductView(cat_id, i);
        });
    };

我需要使用<div>等类附加到每个class="item-1_1"元素,点击app.renderPageProductView(1,1);上的函数

有人有解决方案吗? 谢谢!

2 个答案:

答案 0 :(得分:6)

让我们让您更轻松。

他们所有使用相同的类:.category-list,然后将类别添加为数据元素(data-cat='foo'data-id='bar'

然后你可以这样做:

$(document).on('click','.category-list', function(){
     var data = $(this).data();

     app.renderPageProductView(data.cat, data.id);
});

您可以执行以下操作来设置所有内容:

for(id in category){
   for(var i = 0; i < category[id].length; ++i){
        var img = category[id][i]["img"];
        var title = category[id][i]["titolo"];
        var price = category[id][i]["prezzo"];

        $('#content').append('<div class="category-list" data-id="'+ i +'" data-cat="'+ id +'"><img src="' + img + '"><p>' + title +'</p><p>€' + price + '</p></div>');
   }
}

答案 1 :(得分:0)

尝试将索引存储到数据属性中。完成循环后执行单击,这样我就是最大值。

试试这段代码:

   $('#content').append('<div data-index="' + i + '" class="category-list item-'+ cat_id + '_' + i +'"><img src="' + img + '"><p>' + title +'</p><p>€' + price + '</p></div>');

   //From here begins my problem:
   //When i search fot the class added before and try to append or do anything else, variable i is always 8!
    $('.category-list').click(function(){
         app.renderPageProductView(cat_id, parseInt($(this).attr('data-index'), 10));
    });