我正在使用 html、Javascript 和 CSS 创建一个模拟网站。我想通过按导航栏上的“电视节目”列表从一个页面移动到另一页面(home.html 到 TVShows.html)。通常我只会分配 href,但我想使用 Javascript 来编写此交互。这是我的尝试,但没有成功。 网页:
<li><a id="TVShows" href="#">TV
Shows</a></li>
Javascript:
// Function to handle navigation to TV Shows page
document.getElementById('TVShows').addEventListener('click', function(event) {
event.preventDefault(); // prevent default link behavior
console.log("TV Shows link clicked");
// Redirect to TV Shows page
window.location.href = 'TVShows.html';
});
我尝试过不同的写法,但没有成功。
<!doctype html>
<li><a id="TVShows" href="#">TV
Shows</a></li>
<script>
// Function to handle navigation to TV Shows page
document.getElementById('TVShows').addEventListener('click', function(event) {
event.preventDefault(); // prevent default link behavior
console.log("TV Shows link clicked");
// Redirect to TV Shows page
window.location.href = 'TVShows.html';
});
</script>
这个独立页面可以工作。所以错误在其他地方,在您没有向我们展示的其他代码中。