javascript 为什么我的 onclick 事件没有在 Firefox 中注册?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10852165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:15:20  来源:igfitidea点击:

Why is my onclick event not registered in Firefox?

javascriptfirefoxonclickhtml-lists

提问by hdayi

I have a list item with an onclickevent. It runs in Chrome and Internet Explorer, but not Firefox. Any suggestions?

我有一个带有onclick事件的列表项。它可以在 Chrome 和 Internet Explorer 中运行,但不能在 Firefox 中运行。有什么建议?

<li onclick="alert('test');">test test<br></li>

回答by Jason Stackhouse

This works fine for me in Firefox.

这在 Firefox 中对我来说很好用。

Check this:

检查这个:

  1. JavaScript is enabled in your browser.

  2. Try adding a return false;statement in your tag.

  1. 您的浏览器已启用 JavaScript。

  2. 尝试return false;在您的标签中添加一条语句。

Or a function like this:

或者像这样的函数:

function test() {
    //your code here
    return false;
}
  1. Or use this:
  1. 或者使用这个:

<a href="#" onclick="alert('hi');">Link</a>

<a href="#" onclick="alert('hi');">Link</a>

or this

或这个

<a href="javascript:void(0)" onclick="alert('hi');">Link</a>

<a href="javascript:void(0)" onclick="alert('hi');">Link</a>

回答by hdayi

I was trying to minimize my html code to send a complete code to simulate the error as Boris Zbarsky requested. Then I found my mistake.

我试图最小化我的 html 代码以发送完整的代码来模拟 Boris Zbarsky 请求的错误。然后我发现了我的错误。

I was using marquee tag which has been deprecated. Now I am going to use jQuery instead of it.

我使用的选框标签已被弃用。现在我将使用 jQuery 而不是它。

thx

谢谢

回答by daniella

In Firefox, the event objectis not global. You have to access it within your script tags not in html.

Firefox 中,事件对象不是全局的。您必须在脚本标签中而不是在 html 中访问它。

onclickworks likes this

onclick作品喜欢这个

<li id="alert">test<br></li>

<script>
  document.getElementById("alert").addEventListener("click", function( event ) {
    alert('test');
  }, false);
</script>

回答by user1133275

Attributes can be ignored by Firefox when it is served invalid HTML, use https://validator.w3.org/to clean up the HTML.

当提供无效的 HTML 时,Firefox 可以忽略属性,使用 https://validator.w3.org/清理 HTML。