javascript - 点击功能上的javascript根本不起作用
问题描述
第二个功能,应该带我去player2.html
,由于某种原因不起作用。语法或格式有什么错误吗?
document.getElementById("start").onclick = function()
{
location.href="player.html";
}
//**>>>**This doesn't work. Button does nothing when clicked****
document.getElementById("next").onclick = function()
{
location.href="player2.html";
}
document.getElementById("startgame").onclick = function()
{
location.href = "gameboard.html";
}
这是 index.html
<div class="container">
<header>
<h1>
Tic Tac Toe
</h1>
</header>
<div class="frame">
<div>
<button id="start">Start</button>
</div>
<div>
<button>Exit</button>
</div>
</div>
</div>
<script src="main.js"></script>
这是 player.html
<div class="container">
<header>
<h1>Tic Tac Toe</h1>
</header>
<div class="frame">
<label for="player">Enter player1 name : </label>
<input type="textbox" id="player">
<div>
<button id="next">Next</button>
</div>
</div>
</div>
<script src="main.js"></script>
解决方案
当您加载页面时,以下代码会导致错误,player.html
因为该页面上没有 id 为“start”的元素。
document.getElementById("start").onclick = function()
{
location.href="player.html";
}
您将在 JS 文件的顶部收到一个错误,这会破坏其他按钮。我推荐 jQuery,因为在绑定 onclick 事件时找不到 ID 时不会出错。在 jQuery 中执行此操作。
$('#next').click(function(){
location.href="player.html";
});
如果你不想使用 jQuery,这里是 JavaScript 方式
var elem = document.getElementById("start");
if(elem){
elem.onclick = function()
{
location.href="player.html";
}
}
推荐阅读
- python - 当 CPU 被过度使用时,弱引用对象不再存在
- c# - 两列中的 OrderBy 记录 ASC
- vagrant - Vagrantfile 未在具有特殊字符的路径中加载
- spring-boot - Spring Boot/Java 将枚举值映射到 RequestParam
- javascript - 如何在我的俄罗斯方块游戏中设置高分 javascript html css
- conv-neural-network - CNN如何处理多张图像
- c++ - 如何在 Windows 上静态构建和包含 wolfssl?
- unity3d - Unity 问题:将世界坐标转换为我的 Radar 的 3D 雷达坐标
- react-native - 如何制作 react-native 闹钟?
- c++ - Boost Xpressive - 字段“m_rx”的类型不完整