我如何让这个 javascript 部分工作

问题描述 投票:0回答:1

我正在使用 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'; 
});

我尝试过不同的写法,但没有成功。

javascript html css reactjs
1个回答
0
投票
<!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>

这个独立页面可以工作。所以错误在其他地方,在您没有向我们展示的其他代码中。

© www.soinside.com 2019 - 2024. All rights reserved.