点击功能上的javascript根本不起作用

标签 javascript html

第二个函数,应该带我到 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,因为当绑定(bind) 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";
    }
}

关于点击功能上的javascript根本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50474959/

相关文章:

javascript - react : Check if key is unique

html - 单击时显示隐藏文本

javascript - 渲染时未检查 Vuejs 共享 radio 组件

javascript - 根据另一个 json 数组将 observableArray 映射到 Multiple SELECT

javascript - 延迟加载/延迟 X JavaScript 数量

javascript - Jquery DataTables Live DOM 排序在复选框列上不起作用

jquery - float 操作按钮不起作用?

javascript - 提高 html canvas mousemove 图像蒙版的性能

html - 在 CSS Grid 中将绝对定位的元素居中

包含 html-template 时 Javascript 不执行