javascript - 未能在“节点”上执行“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>
解决方案
@Batu.Khan 意外地指出了我正确的方向,所以我在这里发布了解决方案。
原来不是这样的。运行
labelFocusLost()
将从 DOM 中删除元素。但是,一旦元素消失,焦点也会丢失在元素上,因此labelFocusLost()
会再次触发。除了,将不再有要删除的元素。解决这个问题非常简单;而不是 runninglabelFocusLost()
,只需通过 using 强制元素失去焦点.blur()
,这将反过来运行labelFocusLost()
并删除元素。由于焦点已经被移除,它不会运行第二次。
这个修复最终只是
if (exit) { event.target.blur() }
推荐阅读
- python - KilledWorker 异常
- python - 使用 oauth2 的烧瓶登录会话不起作用
- electron-builder - 无法下载应用程序
- sql-server - 加速将数据从 SQL Server 引用/导入 Excel 的代码
- python - 如何在 Python 中将 JSON 字符串值转换为小写?
- laravel - 如何正确设置 PhpStorm?Сan't run PHPUnit on Laravel 8 on Windows 10. 调用未定义函数 Tests\Unit\is_id_term()
- c++ - 如何加快程序执行速度?
- javascript - Vue 3 Composition API,使用 valueAsDate 属性设置日期输入
- sql - SQL试图分隔数据库字段中的条目值
- multithreading - Nasm - 在不同的线程中更改变量