JS 函数不更新 HTML 字符串

JS function does not update HTML string

本文关键字:HTML 字符串 更新 函数 JS      更新时间:2023-09-26

我对JS和HTML很陌生(~20小时前开始),并且已经有一个问题:下面你可以看到我的代码。正如一个教程所说,单击按钮将更改状态线文本。但是出了点问题,我无法弄清楚。

    <!DOCTYPE html>
<html>
<head>
<title>Некое подземелье</title>
</head>
<body>
<p id="statusLine">Вы попали в подземелье.</p>
<button type="button" onclick="goDeeper()">Идти глубже в подземелье</button>
<script>
    function goDeeper()
     {
       var nextEvent=(Math.floor(Math.random()*10+1));
       switch(nextEvent){
        case'1':
            document.getElementById("statusLine").innerHTML="Вам на пути попался гоблин!";
            break;
                }
     }
</script>
</body>
</html>

所以,有些不对劲。我应该怎么做才能解决这个问题?

尝试使 case 语句与数字1匹配,而不是字符串'1'

function goDeeper()
{
    var nextEvent = Math.floor(Math.random()*10+1);
    switch(nextEvent) {
        case 1:
            document.getElementById("statusLine").innerHTML="Вам на пути попался гоблин!";
            break;
    }
}

或者就此而言,如果只需要匹配一个条件,只需摆脱switch并使用简单的if块:

function goDeeper()
{
    var nextEvent = Math.floor(Math.random()*10+1);
    if (nextEvent == 1) {
        document.getElementById("statusLine").innerHTML="Вам на пути попался гоблин!";
    }
}
What I understand you want to change the text on click button so Try this 
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="Hello World";
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>`enter code here`
</body>
</html>
Refrence Link : http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick