JavaScript 不响应元素点击?
这是有问题的代码片段:
...
var btnClick = document.getElementById("button");
btnClick .addEventListener("click", func, false);
}
function func()
{
alert("This works");
}
我没有收到任何警报框。看到任何问题吗?
This is the piece of code in question:
...
var btnClick = document.getElementById("button");
btnClick .addEventListener("click", func, false);
}
function func()
{
alert("This works");
}
I don't get any alert box. See any problems?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您使用哪种浏览器? IE 在版本 9 之前不支持
.addEventListener()
,因此您需要这样说:并且不要在没有使用
.getElementById()
的元素上使用.getElementById()
尚未被解析,即,将上述代码放在 document.ready 或 load 事件处理程序中,或者将其放在页面源中的元素之后。Which browser are you using? IE doesn't support
.addEventListener()
until version 9, so you need to say something like this:And don't use
.getElementById()
on an element that hasn't been parsed yet, i.e., put the above code either in a document.ready or load event handler, or put it after the element in the page source.这是因为你没有初始化它......!!!
Its because of the reason that you have not initialised it....!!!
如果执行以下所有操作,这将起作用:
addEventListener
的较新浏览器中运行此代码(旧版本的 IE 不支持)。id="button"
的元素。.addEventListener
之前btnClick
后面的空格。您可以在这里看到它的工作原理: http://jsfiddle.net/jfriend00/HQ24Z/
If you do all of the following, this will work:
addEventListener
(old versions of IE don't support that).id="button"
.btnClick
before.addEventListener
.You can see it work here: http://jsfiddle.net/jfriend00/HQ24Z/
切勿使用“按钮”等非常通用的术语,因为它们往往是保留的,如果您绝对确定它应该有效,您最终会抓狂。使用 id 属性的描述性值,例如“form_4_button_submit”。
还有一个如何进行跨浏览器事件处理的示例......
Never use very generic terms such as 'button' as they tend to be reserved and you'll end up ripping your hair out if you're absolutely sure it should work. Use descriptive values for id attributes such as 'form_4_button_submit'.
Also an example of how to do cross-browser event handling...