3

I am facing a strange problem with dynamically replacing controls using javascript in Google Chrome. The replaced controls dont show up in UI but when i use developer tools i am able to locate the replaced element but it does not show up until i close the developer tools. once i open and close developer tools the issue is no longer replicatable until i refresh the page.

This happens only in cases where i am trying to replace outerHTML of an element.

I first tried using jquery's replaceWith api, that dint help so i switched to the following script -

function chromeOuterHTML(oldElem, outerhtml)
{
var el = document.createElement('div');
el.innerHTML = outerhtml;
var parentNode = oldElem.parentNode;
var range = document.createRange();
        range.selectNodeContents(el);
        var documentFragment = range.extractContents();
        parentNode.insertBefore(documentFragment, oldElem);
        parentNode.removeChild(oldElem);
}

I dont think that its a problem with my javascript since the problem is specific to chrome and also happens in only certain cases.

Any help would be greatly appreciated

4

1 回答 1

1

与其说是解决方案,不如说是一种诊断工具,但是您是否尝试过延迟 insertBefore?

function chromeOuterHTML(oldElem, outerhtml)
{
var el = document.createElement('div');
el.innerHTML = outerhtml;
var parentNode = oldElem.parentNode;
var range = document.createRange();
        range.selectNodeContents(el);
        var documentFragment = range.extractContents();
            setTimeout(function () {    
                parentNode.insertBefore(documentFragment, oldElem);
                parentNode.removeChild(oldElem);
    }, 1);
}

在某些情况下(我不完全理解),如果连续发生得太快,DOM 操作可能会失败。此修改将延迟(仅 1 毫秒)插入 - 它可能会有所作为。也有可能什么都不做!

于 2012-01-23T21:28:43.187 回答