gpt4 book ai didi

javascript - jQuery 追加 onclick 函数

转载 作者:数据小太阳 更新时间:2023-10-29 04:16:09 24 4
gpt4 key购买 nike

我被这个问题卡了一整天了!基本上,我有这个数组:

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

谁有解决办法?谢谢!

最佳答案

让我们让这对您来说更轻松。

它们使用相同的类:.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>');
}
}

关于javascript - jQuery 追加 onclick 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13954971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com