innerHTML包含的书签不能从另一个页面链接到



我使用JavaScript AJAX将文件cards.html包含到父html页面index.html中。
包含的cards.html文件是一张卡片列表,每张卡片都有一个书签,格式为<li id="byx-123_shapes">。当我从另一个页面超链接到书签时,浏览器的位置不是在书签上,而是在页面的顶部。如果我手动插入cards.html到index.html超链接工作正常。浏览器似乎没有意识到书签,因为它们是通过AJAX导入的,而不是在加载index.html时存在的。

Cards.html包含在index.html.

<section id="cards">
<!-- INSERT CARDS HERE -->
<ul>
<li id="byx-123_shapes" class="byx-book-tile byx-box">

<figure>
<img src="books/123_shapes/res/icon.png">
</figure>

<h2>
123 Shapes
</h2>
<p>
Placeholder for a book that is still being written.
</p>
<a href="previews/123_shapes_view.html">Preview Book</a>
</li>
.... more cards ...
<li id="byx-zoo_friends" class="byx-book-tile byx-box">

<figure>
<img src="books/zoo_friends/res/icon.png">
</figure>

<h2>
Zoo Friends
</h2>
<p>
Placeholder for a book that is still being written.
</p>
<a href="previews/zoo_friends_view.html">Preview Book</a>
</li>
</ul>
</section>
...

JavaScript加载cards.html

// Uses AJAX to load cards.html
// Works but messes up card bookmarks
const xhr = new XMLHttpRequest();
const cards = document.getElementById('cards');
xhr.onload = function() {
if (this.status == 200) {
cards.innerHTML = xhr.responseText;
} else {
console.warn('Could not load cards');
};
};
xhr.open('get', 'cards.html');
xhr.send();

一个超链接的例子,当通过AJAX包含时不能工作,但当手动插入卡片时可以工作。

https://...//index.html#byx-zoo_friends

谁能解释一下为什么会发生这种情况以及如何修复它?

当您加载index.html#bookmark时,它会在加载页面后立即滚动到书签。但是AJAX请求还没有完成,所以还没有加载书签。

您应该在xhr.onload函数中添加代码,以便在插入HTML

后滚动到书签。
xhr.onload = function() {
if (this.status == 200) {
cards.innerHTML = xhr.responseText;
if (window.location.hash) {
let target = document.querySelector(window.location.hash);
if (target) {
target.scrollIntoView();
}
}
} else {
console.warn('Could not load cards');
};
};

最新更新