简体   繁体   English

jQuery replaceWith不适用于谷歌浏览器

[英]jquery replaceWith not working on google chrome

I am facing a strange problem with dynamically replacing controls using javascript in Google Chrome. 我在使用Google Chrome浏览器中的javascript动态替换控件时遇到一个奇怪的问题。 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. 被替换的控件不会显示在UI中,但是当我使用开发人员工具时,我能够找到被替换的元素,但是直到我关闭开发人员工具时,它才显示出来。 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. 仅在我要替换元素的externalHTML的情况下才会发生这种情况。

I first tried using jquery's replaceWith api, that dint help so i switched to the following script - 我首先尝试使用jquery's replaceWith api,这对dint有帮助,所以我切换到以下脚本-

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. 我认为这不是我的JavaScript的问题,因为该问题特定于Chrome,并且仅在某些情况下才会发生。

Any help would be greatly appreciated 任何帮助将不胜感激

More a diagnostic tool than a solution, but have you tried delaying your insertBefore? 除解决方案外,它还提供了更多的诊断工具,但您是否尝试过延迟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);
}

In some situations (that I don't fully understand), DOM manipulations can fail if they happen in too quick a succession. 在某些情况下(我不完全了解),如果DOM操作连续进行得太快,则可能会失败。 This modification will delay (only by 1ms) the insert - it's possible that it will make a difference. 此修改将延迟插入(仅延迟1ms)-可能会有所作为。 It's also possible it'll do nothing! 也有可能什么都不做!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM