首页 > 解决方案 > 点击功能上的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>

标签: javascripthtml

解决方案


当您加载页面时,以下代码会导致错误,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";
    }
}

推荐阅读