简体   繁体   中英

onclick function in loop, executes without clicking

Im fetching data from a blizzard api(working fine) and i have a jquery $each loop to retrieve the data which i then append in a ul. i want to add a button within every time the loop gives out data to an object. the problem is that when i use onclick='"+myfunction(param)+"' inside the loop, it will execute the function before i have pressed the button the onclick is attached to. when i check the browser it says onclick="undefined". here is the code:

let tid;
function reply_click(clicked_id){
console.log(clicked_id);
}
$('#searchnow').bind('click',
function (){
function kaldapiclass(){
    // console.log("card");
    var classSelect=$('#thisclass').val();
    $.getJSON('https://us.api.blizzard.com/hearthstone/cards? 
locale=en_US&access_token=hidden&class='+classSelect, function(data) {
        $('#kortliste').empty();
        $.each( data.cards, function(i, card) {

            $()
            $('#kortliste').append("<li id='" + card.id + "'><img src='" + card.image + "'><p>"+ 
card.name +"</p><button onclick='"+reply_click(card.id)+"'>HERE</button></li>");
        });
    });
};
clearTimeout(tid);
tid=setTimeout(kaldapiclass, 500);

});

ty for your time -Morten

The code you entered will actually execute the function. So, instead of:

"<button onclick='"+reply_click(card.id)+"'>HERE</button>"

you should just define the element the way you would place it in dom:

"<button onclick='reply_click("+card.id+")'>HERE</button>"

Only the card.id should be dynamic.

I would also suggest to append html only once, this way:

var toAppend = '';
$.each( data.cards, function(i, card) {
    toAppend += "<li id='" + card.id + "'><img src='" + card.image + "'><p>" + card.name + "</p><button onclick='reply_click(" + card.id + ")'>HERE</button></li>";
});
$('#kortliste').html( toAppend );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM