首页 > 解决方案 > 未能在“节点”上执行“replaceChild”,但没有失败?

问题描述

使用时出现此错误.replaceChild(),尽管我在使用时也遇到了类似的错误.outerHTML。错误只在运行时弹出labelSubmit();直接运行labelFocusLost()不会报错。令人沮丧的是,它并没有被替换掉。它确实有效,但 Chrome 无论如何都会抛出错误。它在技术上是功能性的,所以如果这只是一个奇怪的 Chrome 错误,这没什么大不了的,但如果可能的话,我真的更愿意在我的日志中保持零错误。

function labelSubmit(literal) {
    const key  = event.key.toLowerCase()
    const exit = key == "escape" || key == "enter"

    if (exit) { labelFocusLost(literal) }
}

function labelFocusLost(literal) {
    const param   = literal.split(":")
    const target  = event.target
    const escaped = false

    const prev = {
        index: param[0],
        choice: param[1],
        name: target.value.toLowerCase() || param[2]
    }

    const label = `<label for="tabs-${prev.index}" class="default-text radio-label button ${prev.choice}" onpointerup="tabClick()">${escaped ? param[2] : prev.name}</label>`

    target.parentNode.parentNode.replaceChild(textToHTML(label), target.parentNode)
    //target.parentElement.outerHTML = label
}
<div id="tabs" class="grid-tabs debug">
    <input id="tabs-0" type="radio" name="tabs" class="no-display" checked="">
        <div class="default-text input-wrapper">
            <span class="clear input-measure">defaualt tab</span>
            <input maxlength="15" class="clear default-text input" placeholder="input new name here" value="defaualt tab" oninput="labelInput('input new name here')" onkeydown="labelSubmit('0:button-choice:defaualt tab')" onfocusout="labelFocusLost('0:button-choice:defaualt tab')" style="width: 113px;">
        </div>
    <input id="tabs-1" type="radio" name="tabs" class="no-display" />
        <label for="tabs-1" class="default-text radio-label button" onpointerup="tabClick()">default tab</label>
    <button data-choice="" class="clear default-text button" onclick="addTab()">+</button>
</div>

标签: javascripthtml

解决方案


@Batu.Khan 意外地指出了我正确的方向,所以我在这里发布了解决方案。

原来不是这样的。运行labelFocusLost()将从 DOM 中删除元素。但是,一旦元素消失,焦点也会丢失在元素上,因此labelFocusLost()会再次触发。除了,将不再有要删除的元素。解决这个问题非常简单;而不是 running labelFocusLost(),只需通过 using 强制元素失去焦点 .blur(),这将反过来运行labelFocusLost()并删除元素。由于焦点已经被移除,它不会运行第二次。

这个修复最终只是

if (exit) { event.target.blur() }

推荐阅读