0

我想为img里面的每个元素的 cookie 添加一个删除选项for-loop。问题是一切ids总是来自最后一个对象。

我试过的:

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); 总是打印我创建的所有 img 元素的最后一个 id。

4

1 回答 1

1

这与闭包没有直接关系,而是与您的变量header在全局范围内有关。当你声明一个新变量时,你应该使用var关键字,否则它被认为是全局对象的一个​​属性(window)。

如果您启用严格模式(通过添加"use strict";到代码顶部或函数顶部),您将被告知此类错误。

要清楚,你需要改变

header = document.createElement('img');

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

(并且应该对所有变量执行相同的操作)

于 2013-09-21T16:45:39.273 回答