我想更改一些元素的outerHTML,然后将其传递给一个函数,以便函数可以对它做一些事情:
const bars = document.getElementsByClassName('bar');
for (let i = bars.length - 1; i >= 0; i -= 1) {
const bar = bars[i];
bar.outerHTML = `<h1 class="bar">${bar.innerHTML}</h1>`;
const foo = new Foo(bar);
// ... some code
foo.doFoo();
}
function Foo (bar) {
this.bar = bar;
this.doFoo = function() {
this.bar.innerHTML = `Foo${this.bar.innerHTML}`;
console.log('doFoo:', this.bar.innerHTML);
// expected on page: "Dog" --> "FooDog", "Turtle" --> "FooTurtle". This doesn't happen.
}
}
&#13;
<p class="bar">Dog</p>
<p>Cat</p>
<p class="bar">Turtle</p>
&#13;
然而,虽然在outerHTML发生变化后DOM发生了变化,但变量bar
仍在引用&#34; old&#34;元素的(未更改的)版本,当然不再存在于DOM中。因此,无法再更改DOM内容。
MDN上对此行为的说明:
虽然元素将在文档中被替换,但是其中的变量 设置的outerHTML属性仍将保持对原始的引用 元件
我怎样才能实现Foo-Object仍然知道DOM中的正确元素,而不必再次查询DOM?
答案 0 :(得分:0)
一个选项可能是获取对您要更改nextElementSibling
的每个outerHTML
元素的引用。我们称之为next
。
然后,在您更新outerHTML
后,您将获得对新元素的更新引用:
next.previousElementSibling
或者,实际上,如果您更新的元素已经是最后一个且nextElementSibling
已返回undefined
next ? next.previousElementSibling : bar.parentElement.lastChild
const bars = document.getElementsByClassName('bar');
for (let i = bars.length - 1; i >= 0; i -= 1) {
const bar = bars[i];
const next = bar.nextElementSibling;
bar.outerHTML = `<h1 class="bar">${bar.innerHTML}</h1>`;
const foo = new Foo(next.previousElementSibling || next.parentElement.lastChild);
// ...
foo.doFoo();
}
function Foo (bar) {
this.bar = bar;
this.doFoo = function() {
this.bar.innerHTML = `Foo${ this.bar.innerHTML }`;
console.log('doFoo:', this.bar.innerHTML);
// expected on page: "Dog" --> "FooDog", "Turtle" --> "FooTurtle". This doesn't happen.
}
}
&#13;
<p class="bar">Dog</p>
<p>Cat</p>
<p class="bar">Turtle</p>
&#13;