简体   繁体   English

JavaScript 未在脚本标签内执行

[英]JavaScript not executing inside script tag

This is extremely embarrassing as this is probably the simplest code you'll ever see that someone could be having a problem with;这非常令人尴尬,因为这可能是您见过的最简单的代码,但有人可能会遇到问题; I have this simple html document:我有这个简单的 html 文档:

<script>
    function rollDie() {
        let result = Math.round(Math.random() * 6);
        return result < 1 ? result + 1 : result;
    }

    function updateView() {
        let getResult = rollDie();
        console.log(getResult);
        document.getElementById('d6-a').innerHTML = getResult;
    }
</script>
<input id='d6-a' name="d6-a" type='submit' onsubmit="updateView" />

That's it -- literally just that.就是这样——字面意思就是这样。 Yes that's the whole document.是的,这就是整个文件。 No <,DOCTYPE>, no <html>, no <head>;没有 <,DOCTYPE>,没有 <html>,没有 <head>; no <body>, but I was (and still am) under the impression that that is all fine and any modern browser should compile.没有<body>,但我(现在仍然)认为这一切都很好,任何现代浏览器都应该编译。 render and run this with no issue regardless.无论如何渲染和运行它都没有问题。

And it does render just fine;它确实渲染得很好; but when I click the input nothing happens.但是当我点击输入时没有任何反应。 The HTML is not updated and nothing is logged in the console (not even any errors). HTML 未更新,控制台中未记录任何内容(甚至没有任何错误)。 Which tells me the scripts are just being straight ignored, but why?这告诉我脚本只是被直接忽略了,但是为什么呢? I have tried: moving the <script> to the bottom of the document, onsubmit="updateView", onsubmit="updateView()", onclick (each as before), changing the input element to <button> (how I originally had it), changing the input element to <div>.我试过:将 <script> 移动到文档的底部,onsubmit="updateView", onsubmit="updateView()", onclick (每个都像以前一样),将输入元素更改为 <button> (我原来的它),将输入元素更改为 <div>。 It.它。 Doesn't.没有。 Work.工作。 Please help?请帮忙? (I'm using Google Chrome btw) (顺便说一句,我正在使用谷歌浏览器)

onsubmit is not applicable for input tag.You should wrap it in a form element & the onsubmit event handler must be added to form element. onsubmit 不适用于输入标签。您应该将其包装在表单元素中,并且必须将 onsubmit 事件处理程序添加到表单元素中。

<form onsubmit="updateView()">
        <input id='d6-a' name="d6-a" type='submit'  />
    </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM