为什么我的JS不会修改这个HTML?

时间:2014-10-21 16:04:53

标签: javascript html

我正在制作一个基本的摇滚,纸张,剪刀游戏,它到目前为止工作,但我真的希望它接受userInput的“名称”然后问候用户像“欢迎,名字”

但它不起作用下面是代码中没有突出显示的部分

<!DOCTYPE html>
<html>
<head>
    <script src="myJS.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!--right here-->
    <p id = "Name"> Welcome, Name</h1>
<!--ends here-->
    <a href="http://cooltext.com"><img src="http://images.cooltext.com/3974705.png"
     width="1056" height="81" alt="Rock Paper Scissors" /></a>

    <button onclick="RPS()" <a href="#" class="style" >Click Me To Play!</a></button>
    <p><br<br></p>
    <p id="counter">You won 0 times!</p>
</body>

这是JS

var timesWon = 0;
//below = part that won't work//
//check PLEASE
var name = "Person";
name = prompt("What's your name?");
document.getElementById("Name").innerHTML = "Welcome, "+name + "!";
document.write(name);
//END OF UNWORKING PART
var counter = 0;
function RPS()
{
     var userChoice = prompt("So, "+ name + ", rock, paper, or scissors?        (All LowerCase Please!)");
var computerChoice = Math.random();
var opposition = "";

if(computerChoice > 0.67)
{
    opposition  = "rock";

    if(userChoice == ("rock"))
    {
        alert("you tied!");
    }
    else if(userChoice == "paper")
    {
        alert("you won!");
        counter++;
        document.getElementById("counter").innerHTML = "You won "+counter + " times";
    }
    else if(userChoice ==("scissors"))
    {
        alert("you lost!");
    }
}
else if(computerChoice > 0.34)
{
    opposition  = "paper";

    if(userChoice == ("rock"))
    {
        alert("you won!");
        counter++;
        document.getElementById("counter").innerHTML = "You won "+counter + " times";

    }
    else if(userChoice == "paper")
    {
        alert("you tied!");
    }
    else if(userChoice ==("scissors"))
    {
        alert("you lost!");
    }
}
else
{
    opposition  = "scissors";

    if(userChoice == ("rock"))
    {
        alert("you lost!");
    }
    else if(userChoice == "paper")
    {
        alert("you won!");
        counter++;
        document.getElementById("counter").innerHTML = "You won "+counter + " times";

    }
    else if(userChoice ==("scissors"))
    {
        alert("you tied!");
    }
    else 
    {
        alert("Invalid Input");
    }
}

}

3 个答案:

答案 0 :(得分:1)

游戏一开始,您就会立即开始运行。把它放在它自己的功能中:

function getUserName(){
    window.name = prompt("What's your name?");
    document.getElementById("Name").innerHTML = "Welcome, "+name + "!";
}

然后在身体负载上调用该函数:

<body onload="getUserName();">

此外,您必须使用相应的标记关闭name元素。您有</h1>而不是</p>,并且不使用document.write(),只有在您拥有体内<script>标记的情况下才能使用它。

答案 1 :(得分:0)

javascript可能正在尝试将文本分配给尚未呈现的元素。尝试找出一种方法将innerHTML赋值放在body标记的末尾。您需要将其包装在另一个脚本标记中。

答案 2 :(得分:0)

代码尝试在加载HTML之前运行。试试这个:

window.onload = function () {
var name = "Person";
name = prompt("What's your name?");
document.getElementById("Name").innerHTML = "Welcome, " + name + "!";
}