0

I want to add a delete option for a cookie of each img element inside for-loop. the problem is that all ids are always from the last object.

what I've tried:

function listCookies() {
    var theCookies = document.cookie.split(';');
    var aString = '';
    for (var i = 1; i <= theCookies.length; i++) {
        (function (i) {
            if (theCookies[i - 1].indexOf("pauseCookie-") >= 0) {
                cookieArray = theCookies[i - 1].split("=");
                theCookie = $.trim(cookieArray[0]);
                cookieInfo = $.cookie($.trim(theCookie));
                cookieInfo = cookieInfo.split("^");

                ...

                htmlCode = "<div id='pauseDiv-" + theCookie + "'><a href='" + cookiePath + "'>" + cookieTitle + "</a> (" + pauseInfo + ") </div><br />";
                $("#cookiesContent").append(htmlCode);

                header = document.createElement('img');
                header.id = 'delImg' + theCookie;
                header.style = 'cursor:pointer';
                header.src = delImage;

                header.onclick = function () {
                    alert("#pauseDiv-" + header.id);
                    //$.removeCookie(theCookie,{path:'/'});
                    $("#pauseDiv-" + theCookie).html("<div class=\"pauseDivResponse\">Deleted</div>");
                }

                document.getElementById("pauseDiv-" + theCookie).appendChild(header);

            }
        })(i);
    }
}
listCookies();

alert("#pauseDiv-" + header.id); always prints the last id from all img elements I created.

user2783132
  • 225
  • 1
  • 3
  • 16

1 Answers1

1

This is not directly related to closures, but is to do with your variable header being in the global scope. When you declare a new variable, you should use the var keyword, otherwise it is assumed to be a property of the global object (window).

If you enable strict mode (by adding "use strict"; to the top of your code, or the top of the function), you will be told about these sorts of mistake.

To be clear, you need to change

header = document.createElement('img');

to

var header = document.createElement('img');

(and should do the same for all your variables)

Dave
  • 44,275
  • 12
  • 65
  • 105