2017-08-11 65 views
0

我最近开始一个新的项目,所以目前它是非常简单的代码。我认为可能只是和错误,或者我不知道这是一个问题。对于一个更有经验的程序员来说,这应该是一个简单的修复。我的HTML和JavaScript是获得一个基本的JavaScript代码工作

var quotecount = 3; 
 

 
function show() { 
 
    var rand = Math.floor((Math.random() * quotecount) + 1); 
 

 
    if (rand == 1) { 
 
    document.getElementById("disp").innerHTML = "Quote 1"; 
 
    document.getElementById("quotenum").innerHTML = "This is quote 1 out of " + quotecount; 
 
    } 
 

 
    if (rand == 2) { 
 
    document.getElementById("disp").innerHTML = "Quote 2"; 
 
    document.getElementById("quotenum").innerHTML = "This is quote 2 out of " + quotecount; 
 
    } 
 

 
    if (rand == 3) { 
 
    document.getElementById("disp").innerHTML = "Quote 3"; 
 
    document.getElementById("quotenum").innerHTML = "This is quote 3 out of " + quotecount; 
 
    } 
 
}
button { 
 
    background: #fff; 
 
    border: 1px solid #ccc; 
 
    padding: 5px 13px; 
 
    outline:none; 
 
    cursor:pointer; 
 
} 
 

 
button:hover { 
 
    background: #282828; 
 
    color: #fff; 
 
}
<!DOCTYPE html> 
 
<html> 
 

 
<body> 
 
    <button id="quoteshow" onclick="show">Click me to show a quote!</button> 
 

 
    <p id="disp"></p> 
 
    <p id="quotenum"></p> 
 
</body> 
 

 
</html>

+0

什么问题? – clabe45

+0

@ clabe45它不起作用。当我点击按钮时,没有任何反应。 –

+0

你有没有试过打开JavaScript控制台? – clabe45

回答

1

您需要在括号中的元素你onclick调用添加到show

<button id="quoteshow" onclick="show()">Click me to show a quote!</button> 
0

var quotecount = 3; 
 

 
function show() { 
 
    var rand = Math.floor((Math.random() * quotecount)) + 1; 
 

 
    if (rand == 1) { 
 
     document.getElementById("disp").innerHTML = "Quote 1"; 
 
     document.getElementById("quotenum").innerHTML = "This is quote 1 out of " + quotecount; 
 
    } 
 

 
    if (rand == 2) { 
 
     document.getElementById("disp").innerHTML = "Quote 2"; 
 
     document.getElementById("quotenum").innerHTML = "This is quote 2 out of " + quotecount; 
 
    } 
 

 
    if (rand == 3) { 
 
     document.getElementById("disp").innerHTML = "Quote 3"; 
 
     document.getElementById("quotenum").innerHTML = "This is quote 3 out of " + quotecount; 
 
    } 
 
}
<p id="disp"></p> 
 
<p id="quotenum"></p> 
 

 
<button onclick="show()">Click me</button>

添加点击按钮。