在谷歌关闭中编写的事件侦听器中单击事件不起作用?



我是Java脚本的新手,我的问题是当我在chrome浏览器控制台中尝试这个JS时它可以工作,但是在我的JS文件中它不起作用

我附上了代码,对于HTML设计,我使用了google MDL,对于JS,我使用了Google Closure

.HTML:

<HTML>
<head>
<script src="../closure-library/closure/goog/base.js"></script>
<script src="../js/add.js"></script>
<script src="../js/material.js"></script>
<link rel="stylesheet" href="../css/material.css">
<link rel="stylesheet" href="../css/test_add.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div>
<button id="add" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect">
<i class="material-icons">add</i>
</button>
</div>
</body>
</HTML>

.JS:

goog.provide('sample.add');
goog.require('goog.dom');
goog.require('goog.events');
sample.add = function() {
self = this;
};
goog.inherits(sample.add, goog.base);
sample.add.prototype.bindEvent = function() {
goog.events.listen(goog.dom.getElement('add'),
goog.events.EventType.CLICK, function(e) {
alert("HAPPY");
});
};

这段代码有什么问题

  1. 当我尝试没有goog.provide并向所有人goog.require它的显示错误时
  2. 当我使用它时,对点击事件没有反应
  3. 还有其他最好的资源可以在网上看到吗

请帮助我

所以我要在这里改变一些事情。

最大的问题是你永远不会调用sample.add或sample.add.bindEvent。

然后,必须将脚本移动到按钮下方,以便在脚本运行时按钮位于页面上。或者你可以使用 JS 来延迟脚本的运行,这取决于你,但我会说,在 body 标签结束之前看到脚本是很常见的。

<HTML>
<head>
<script src="../closure-library/closure/goog/base.js"></script>
<script src="../js/material.js"></script>
<link rel="stylesheet" href="../css/material.css">
<link rel="stylesheet" href="../css/test_add.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div>
<button id="add" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect">
<i class="material-icons">add</i>
</button>
</div>
<script src="../js/add.js"></script>
</body>
</HTML>

另外,我会放弃goog.base调用,除非你特别需要它。如果您确实需要,请解释原因,也许我们可以提供帮助。

最后,我们只需要一些细微的调整;

goog.provide('sample.add');
goog.require('goog.dom');
goog.require('goog.events');
/** @export */
sample.add = function() {
self = this;
self.bindEvent();
};
sample.add.prototype.bindEvent = function() {
goog.events.listen(goog.dom.getElement('add'),
goog.events.EventType.CLICK, function(e) {
alert("HAPPY");
});
};
sample.add();

我想你可以直接调用sample.add.bindEvent,但我觉得这可能只是迈向更大的第一步,你会想走这条路。

最新更新