문제

When I click on element it fires up, but when clicking again on that one does nothing. Refreshing page and clicking again works (till clicking it again). Why?

When div is clicked AJAX passes it to PHP in xmlhttp.send();; "click" event is handled by document.getElementById('b_'+countr).addEventListener("click", selectionMade);.

I think it's related with document loading - I want to fire something that is changed by outerHTML; full code provided below:

// 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();
    }
}
도움이 되었습니까?

해결책

innerHTML and outerHTML completely destroy whatever is being changed, and replaces it with the new HTML. In particular this means any event listeners are destroyed, so you have to either not use innerHTML/outerHTML, or reapply the listeners afterward.

Side-note: Instead of attaching an event listener to every tile on the map, attach it to the map itself and use event.target to find which tile was clicked.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top