简体   繁体   English

内联 javascript 代码已弃用的“event.preventDefault()”的好选择

[英]Good alternative for deprecated "event.preventDefault()" for inline javascript code

<button type="submit" class="button-danger" onclick="if(!window.confirm('aaa'))event.preventDefault();">aaa</button>

This is my original code.这是我的原始代码。 PHPStorm is showing that event global variable is deprecated. PHPStorm 显示event全局变量已被弃用。

I do not want to make a separate function to do what I want but I just want this inline version built into the "onclick" attribute of the button.我不想制作一个单独的函数来做我想做的事,但我只想将此内联版本内置到按钮的“onclick”属性中。

Alternative that uses JQuery correctly will be better.正确使用 JQuery 的替代方案会更好。 Any advice will be appreciated.任何建议将被认真考虑。

EDIT: the linked question has answers that make a separate function.编辑:链接的问题具有独立功能的答案。 I want an INLINE version that is built into the onclick.我想要一个内置在 onclick 中的 INLINE 版本。 I don't want to make my code long.我不想让我的代码变长。

To start with, you really shouldn't use inline handlers if you want to be writing decent maintainable modern JavaScript.首先,如果你想编写体面的、可维护的现代 JavaScript,你真的不应该使用内联处理程序。 They have a plethora of problems including usually only being able to reference global identifiers (such as window.event ).它们有很多问题,包括通常只能引用全局标识符(例如window.event )。 I'd strongly recommend attaching the event handler properly using JavaScript.我强烈建议使用 JavaScript 正确附加事件处理程序。

 $('button').on('click', (e) => { if (!window.confirm('aaa')) { e.preventDefault(); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <button type="submit" class="button-danger">aaa</button> </form>

If that's really not an option for you, it's just barely possible to do what you want by referencing the arguments for the inline handler.如果这真的不是您的选择,那么通过引用内联处理程序的arguments几乎不可能做您想做的事情。 The first argument will be the event, so arguments[0].preventDefault() will do what you want.第一个参数是事件,所以arguments[0].preventDefault()会做你想做的事。

 <form> <button type="submit" class="button-danger" onclick="if(!window.confirm('aaa')) arguments[0].preventDefault();">aaa</button> </form>

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

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