简体   繁体   English

onclick事件(非内联)不起作用

[英]onclick event (NOT inline) doesn't work

I figured this out a while ago, but all of my files have been deleted and the only backup I have was from a couple weeks ago... anyways, I've followed the book and a few websites on event handling, but I don't know how to remove the inline Javascript. 我前一阵子就知道了,但是我的所有文件都被删除了,而我唯一的备份是几周前的事情……无论如何,我已经按照书和一些网站进行了事件处理,但是我不知道不知道如何删除内联Javascript。 This is what I've already looked at: 这是我已经看过的:

addEventListener vs onclick addEventListener与onclick

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_close http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_close

button.html File: button.html文件:

<html>
<head>
    <script src="window.js"></script>
</head>
<body>
    <button type="button" id="Start Process">Start Process</button>
</body>
</html>

window.js File: window.js文件:

function myFunction() {
    window.open("http://www.w3schools.com");
}

var Process = document.getElementById('Start Process');
Process.onclick = myFunction;

The code seems to work fine. 该代码似乎工作正常。 Make sure that you import the <script> at the end of the page. 确保在页面末尾导入<script> Otherwise, the button wouldn't exist at the time when the script loads. 否则,脚本加载时该按钮将不存在。

<html>
<head>
     <!-- Remove the script from here -->
</head>
<body>
    <button type="button" id="Start Process">Start Process</button>

    <!-- Place the script here -->
    <script src="window.js"></script>
</body>
</html>

If it still doesn't work, try removing the space from the id . 如果仍然无法使用,请尝试从id删除空格。

In the HTML: 在HTML中:

<button type="button" id="StartProcess">Start Process</button>

In JS: 在JS中:

var Process = document.getElementById('StartProcess');

The id attribute shouldn't contain a space. id属性不应包含空格。 According to HTML 4.0 specification for basic types : 根据HTML 4.0规范的基本类型

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). IDNAME令牌必须以字母([A-Za-z])开头,后跟任意数量的字母,数字([0-9]),连字符(“-”),下划线(“ _”) ,冒号(“:”)和句点(“。”)。

And according to HTML5 specification : 并根据HTML5规范

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. 该值在元素的主子树中的所有ID中必须唯一,并且必须至少包含一个字符。 The value must not contain any space characters. 该值不得包含任何空格字符。

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

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