简体   繁体   English

防止默认值不起作用

[英]Preventdefault not working

Hey guys am new to javascript web development.I have been through preventDefault() through my code.But when i used it it returns the error ..My code 大家好,我是javascript网络开发的新手。我已经通过代码访问了preventDefault() 。但是当我使用它时,它返回错误..我的代码

<html>
<body>
function preventDef(event) {
  event.preventDefault();
}

 document.querySelector('a').addEventListener("click", 
preventDef(event),false);

</script>

<a href="www.google.com">click here</a>
</body>
</html>

When i use this code and clicked on the link it redirects me to google.com ..what i need is the event must be blocked my preventDefault() function.. 当我使用此代码并单击链接时,它会将我重定向到google.com。我需要的是,该事件必须被我的preventDefault()函数阻止。

Hope you guys can help me out ..Thanks 希望你们能帮助我..谢谢

You are calling the preventDef function instead of passing it by reference. 您正在调用preventDef函数,而不是通过引用传递它。

document.querySelector('a').addEventListener("click", preventDef, false);
//                                                              ^^^ don't call the function

EDIT: Another issue is that you are running this before the DOM is ready. 编辑:另一个问题是您在DOM准备就绪之前正在运行此程序。 You need to move the <script> tag down to be after the <a> . 您需要将<script>标记向下移动到<a>

<html>
<body>
<a href="www.google.com">click here</a>
<script>
// ^^ did you miss an opening script?
function preventDef(event) {
  event.preventDefault();
}

 document.querySelector('a').addEventListener("click", preventDef, false);
//                                                              ^^^ don't call the function

</script>

</body>
</html>

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

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