【问题标题】:Why DIV changed by `outerHTML` remains unresponsive为什么由`outerHTML`更改的DIV仍然没有响应
【发布时间】:2012-09-10 21:38:00
【问题描述】:

当我点击元素时,它会启动,但当再次点击该元素时,它什么也不做。刷新页面并再次单击有效(直到再次单击它)。为什么?

当点击 div 时,AJAX 在xmlhttp.send(); 中将其传递给 PHP; “点击”事件由document.getElementById('b_'+countr).addEventListener("click", selectionMade); 处理。

我认为这与文档加载有关 - 我想触发由 outerHTML 更改的内容;完整代码如下:

// prepare clicable map
for (x = 1; x <= 16; x++) {
for (y = 1; y <= 16; y++) {
    (function prepareClickableMap() {
        var cords = x + "x" + y;
        var el = document.getElementById(cords);
        el.addEventListener("click", function (e) { B_modeWindow('1', cords) });
    })();
}
}

//passing selection
for (countr = 1; countr <= 256; countr++) {
    document.getElementById('b_'+countr).addEventListener("click", selectionMade);
}


var s;
function selectionMade(e) {
    selection = e.currentTarget.id.split("_"); 
    s = selection[1];
}

// pass edited map info
function B_modeWindow (id,XxY) {  
    if (s !== undefined) {    
        loading();

        var xmlhttp;
        var position = XxY;

        if (window.XMLHttpRequest) {
            xmlhttp=new XMLHttpRequest();
        } else {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        var xy = position.split("x"); 

        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                document.getElementById(XxY).outerHTML=xmlhttp.responseText;  

                hideloading();
            }
        }

        xmlhttp.open("GET","processMapEdit.php?id="+id+"&x="+xy[0]+"&y="+xy[1]+"&s="+s,true);
        xmlhttp.send();
    }
}

【问题讨论】:

    标签: javascript ajax outerhtml


    【解决方案1】:

    innerHTMLouterHTML 完全销毁正在更改的内容,并用新的 HTML 替换它。特别是这意味着任何事件侦听器都会被销毁,因此您必须要么不使用innerHTML/outerHTML,要么之后重新应用侦听器。

    旁注:不要将事件侦听器附加到地图上的每个图块,而是将其附加到地图本身并使用event.target 来查找单击了哪个图块。

    【讨论】:

    • 如何重新申请监听器? + 是不是有点慢?
    • 设置outerHTML后,添加代码附加事件监听器。
    猜你喜欢
    • 2011-03-01
    • 2014-11-12
    • 1970-01-01
    • 2013-07-15
    • 2018-10-20
    • 2021-04-23
    • 2017-06-16
    • 1970-01-01
    • 2015-12-29
    相关资源
    最近更新 更多