javascript - HTML 文件似乎忽略了 javascript 文件

标签 javascript html

所以我按照 here 的指南制作了一个简单的点击游戏。我尝试测试它,由于某种原因,数字没有增加,所以我检查了控制台,它说“clik()未定义”,当我检查加载的文件时,它只显示HTML文件。 为什么不执行JS文件?

Here's the HTML file:

<!DOCTYPE html>
<html>
<body>
<button onclick="clik(1)">Clik to add cliks</button>
<br />
Cliks: <span id="clik">0</span>
<br />
<script src="js/script.js"></script>
</body>
</html> 

And here's the JS file:

var clik = 0;
function clik(num){
    clik = clik + num
   document.getElementById("clik").innerHTML = clik;
};

请记住,这些都不是在线的,我是在本地运行的。 控制台正在输出

The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. 

一旦我点击按钮

TypeError: clik is not a function[Learn More]

最佳答案

var clik = 0;
function clik(num){
    clik = clik + num
   document.getElementById("clik").innerHTML = clik;
};

当这段代码被解析时,有一个名为 clik 的“变量”,而 i 是一个函数

第一次运行此代码

clik = clik + num;

现在 clik 不是一个函数

actually, it's more complicated than that - function definitions are hoisted to the top of the scope, so what is actually happening is that the var clik=0 is replacing the function before it is even run the first time. Your code is equivalent to writing

function clik(num){
    clik = clik + num
   document.getElementById("clik").innerHTML = clik;
};
var clik = 0;

现在,您可以明白为什么 clik 即使对于第一次用户点击也不是一个函数

您的代码应该为 var 使用不同的名称 - 例如 nclik

var nclik = 0;
function clik(num){
    nclik = nclik + num;
   document.getElementById("clik").innerHTML = nclik;
}

作为旁注,请注意我在哪里使用过 ;function {}; 之后不需要使用 ; 并且您应该 在每个语句后面放一个(当然,这是一个风格问题,只是把它放在那里)

关于javascript - HTML 文件似乎忽略了 javascript 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52070849/

相关文章:

javascript - CSS 缩放(带绝对位置)

html - 查看 CSS 边距以进行调试

javascript - 从这个(选定的)div 中选择 child

html - 使用 flexbox 以绝对位置在 div 内居中 div

javascript - 如何使用 jQuery 防止多个下拉列表中出现重复值

javascript - 使用 jQuery 的内联元素的左偏移量

javascript - HTML5 视频幻灯片

javascript - a 关于使用 javascript 的堆栈多维数据集的面试问题

javascript - react js tomcat,未捕获的语法错误 : Unexpected token import

javascript - 使用 jQuery 的独特 anchor 链接