gpt4 book ai didi

javascript - `.replaceChild()` 上 `this` 抛出 NotFoundError : DOM Exception 8

转载 作者:行者123 更新时间:2023-11-28 13:42:59 25 4
gpt4 key购买 nike

我想我会喜欢并在 jQuery 事件期间使用普通 JavaScript。这个想法是,在单击标题时,我想向上滑动一个 div (可以工作)并将单击的标签替换为更大的标题。

根据我所读到的内容,这可能是由于 parentNode 引用一个不是实际父元素的元素引起的,但在检查后它似乎选择了直接位于其上方的元素。

所以...这是代码!

HTML(Jade)

.policy-container
h6.policy-heading Policies
.policy-list
.content-we-are-hiding
.not-actually-important

jQuery

$('.policy-heading').click(function() {
var self = this;

if (this.classList.contains('closed')) {
$(this).next().slideDown(300);

this.parentNode.replaceChild(self, '<h6 class="policy-heading">Policies</h6>');

} else {
$(this).next().slideUp(300);

this.parentNode.replaceChild(self, '<h2 class="policy-heading closed">Policies</h2>');
}
});

一切看起来都很标准。幸运的是,我可以使用 jQuery 来处理这个问题,但是我宁愿在这里使用 vanilla JS。有什么想法为什么这不起作用吗?

最佳答案

正如已经指出的,replaceChild 需要两个节点。

按照您的指定,以下内容将与包装在 jQuery 内的 native JS 一起使用:

$('.policy-heading').click(function () {
var self = this,
h2 = document.createElement('h2'),
h6 = document.createElement('h6');

h2.class = "policy-heading closed";
h2.innerHTML = "Policies";

h6.class = "policy-heading";
h6.innerHTML = "Policies";

if (this.classList.contains('closed')) {
$(this).next().slideDown(300);
this.parentNode.replaceChild(h6, self);
} else {
$(this).next().slideUp(300);
this.parentNode.replaceChild(h2, self);
}
});

关于javascript - `.replaceChild()` 上 `this` 抛出 NotFoundError : DOM Exception 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16570430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com