简体   繁体   中英

How to stop the value of an .each loop being the same when appending buttons to a website?

    var number = 0;
    $.getJSON("blogData.json", function(data) {

    $.each(data, function (index, entry) {
        console.log(index);
        $("#posts").append("<h3>" + entry.title + "</h3>");
        $("#posts").append("<h4>" + entry.desc + "</h4>");
        $("#posts").append("<h4>" + entry.author + "</h4>");
        $("#posts").append("<p>" + entry.post + "</p>");
        $("#posts").append("<br>");
        $("#posts").append('<button onclick=save(number)>Read More</button>');
        $("#posts").append("<br><br>");
        number++;
    });

});

I want to be able to assign a unique value to every button in order to pass this value to other functions. The context of this is a blog stored in a JSON file where the values of the posts are called via index. I wish to be able to view one post individually by clicking on the button for that specific post.

You have used the variable as string type. All what you need is to concatenate the variable's value.

$("#posts").append('<button onclick=save(' + number + ')>Read More</button>');

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