我无法上班去工作

时间:2016-05-26 21:43:23

标签: javascript html onclick

我是HTML / CSS / Java的新手,所以我希望你们中的一些人可以帮我弄清楚为什么我的onclick事件无效!

这是我的HTML代码(有问题的onclick事件位于h3标记下方的div中,靠近包装器div的底部):

<title>My Very First Webpage</title>

<link rel = "stylesheet" type="text/css" href = "1-sheet.css">

<script src = "1-math.js"></script>

<div id = "headerDiv">
    <h1> Math! </h1>
</div>

<div id = "wrapperDiv">
  <div id = "navDiv">
    <div id = "navButtonDiv" class = "buttonDiv"> <a href = "1-home.html"> Home! </a> </div>
    <div id = "navButtonDiv" class = "buttonDiv"> <a href = "1-math.html"> Math! </a> </div>
    <div id = "navButtonDiv" class = "buttonDiv"> <a href = "1-links.html"> Cool Links! </a> </div>
    <div id = "navButtonDiv" class = "buttonDiv"> <a href = "1-videos.html"> Videos! </a> </div>
    <div id = "navButtonDiv" class = "buttonDiv"> <a href = "1-unknown.html"> ??? </a> </div>
  </div>

  <h3> Enter a list of numbers and find its mean, median, and mode! </h3>
  <div id = "enterNumbers" class = "buttonDiv" onclick = "getNumbers()"> Enter numbers </div>
  <div id = "mathButtonDiv" class = "buttonDiv" onclick = "mean()"> Mean </div>
  <div id = "mathButtonDiv" class = "buttonDiv" onclick = "median()"> Median </div>
  <div id = "mathButtonDiv" class = "buttonDiv" onclick = "mode()"> Mode </div>

</div>

这是链接的JS文件(其文件名为“1-math.js”,因此它与上面的脚本标记匹配):

var nums = "";
function getNumbers()
{
  nums = prompt("Enter a list of numbers separated by commas", "Put numbers here");
}


//incomlete

function mean(var numbers)
{
  document.write("mean");
}

function median(var numbers)
{
  document.write("median");
}

function mode(var numbers)
{
  document.write("mode");
}

感谢您提供的任何帮助! :)

1 个答案:

答案 0 :(得分:1)

首先,使用浏览器控制台查看错误等(通常是F12)。

错误原因是您在函数参数中使用var numbers而不只是numbers

这个小提琴可能会有所帮助(显示正确的函数参数,使用console.log,并将nums传递给onclick事件函数):

https://jsfiddle.net/1jkzhxgd/

这是一个内联代码片段,它具有相同的功能(尽管使用内联console.log输出更难...)

var nums = "";
function getNumbers() {
    nums = prompt("Enter a list of numbers separated by commas", "Put numbers here");
}
function mean(numbers) {
    console.log('mean', numbers);
}
function median(numbers) {
    console.log('median', numbers);
}
function mode(numbers) {
    console.log('mode', numbers);
}
<div id="headerDiv">
    <h1> Math! </h1>
</div>

<div id="wrapperDiv">
    <h3> Enter a list of numbers and find its mean, median, and mode! </h3>
    <div id="enterNumbers" class="buttonDiv" onclick="getNumbers()"> Enter numbers </div>
    <div id="mathButtonDiv" class="buttonDiv" onclick="mean(nums)"> Mean </div>
    <div id="mathButtonDiv" class="buttonDiv" onclick="median(nums)"> Median </div>
    <div id="mathButtonDiv" class="buttonDiv" onclick="mode(nums)"> Mode </div>

</div>