defcected; event.preventdefault()的好替代方案"对于内联JavaScript代码

发布于 2025-02-10 04:38:58 字数 352 浏览 2 评论 0原文

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

这是我的原始代码。 phpstorm显示事件全局变量已弃用。

我不想制作一个单独的功能来完成我想做的事情,但是我只希望该按钮的“ onClick”属性内置此内联版本。

正确使用jQuery的替代性会更好。任何建议将不胜感激。

编辑:链接的问题的答案可以单独函数。我想要一个内置版本的内联版本。我不想使我的代码很长。

<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.

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.

Alternative that uses JQuery correctly will be better. 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. I don't want to make my code long.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只为一人 2025-02-17 04:38:58

首先,如果您想编写不错的可维护现代JavaScript,那么您真的不应该使用内联操件。他们有一个大量的问题通常只能参考全局标识符(例如window.event.event) )。我强烈建议使用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>

如果这实际上不是您的选项,那么通过引用参数为Inline Handler来完成您想做的事情。第一个参数将是事件,因此参数[0] .preventDefault()将执行您想要的工作。

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

To start with, you really shouldn't use inline handlers if you want to be writing decent maintainable modern JavaScript. They have a plethora of problems including usually only being able to reference global identifiers (such as window.event). I'd strongly recommend attaching the event handler properly using 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. The first argument will be the event, so arguments[0].preventDefault() will do what you want.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文