javascript - 事件 : "Deprecated symbol used, consult docs for better alternative"

标签 javascript html pycharm dom-events event-listener

PyCharm(我想 WebStorm 和其他 JetBrains IDE 也是如此)在 event 上发出微弱警告已经有一段时间了。我在代码中使用的变量。
例如在下面的代码中

<div id="my-div" onclick="event.preventDefault();">...</div>
PyCharm 显示此消息“已弃用符号,请查阅文档以获得更好的替代方案”。
问题似乎是 event变量指Window.event ,并根据 MDN Web Docs :

You should avoid using this property in new code, and should instead use the Event passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.


我知道正确的解决方法是写在 javascript 标签中:
document.getElementById("my-div").addEventListener("click", function(event) {
  console.log("And use this " + event + " instead");
});
我只是想知道,如果存在的话,在 HTML 代码(onclick 属性)中使用事件的正确方法是什么。

最佳答案

我不知道它对某人是否仍然重要,但在 WebStorm 2020.3 上测试了以下作品,并且 IDE 没有提示弃用。
此外,WebStorm 将事件标识为 Event .
下面的代码片段。

(function() {
    const checkBox = document.querySelector("#id-checkbox");
    checkBox.addEventListener('click', (event) => {
        event.preventDefault();
    }, false);
})();
<head>
    <script src="click.js" defer></script>
</head>
<body>
    <p>Please click on the checkbox control.</p>
    <form>
        <label for="id-checkbox">Checkbox:</label>
        <input type="checkbox" id="id-checkbox"/>
    </form>

    <div id="output-box"></div>
</body>

关于javascript - 事件 : "Deprecated symbol used, consult docs for better alternative",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57696734/

相关文章:

python - 如何组织一个python项目

JavaScript 难题

html - 无法使用 bootstrap CSS 显示内联表单

python - 导入错误 : No module named 'sha'

python - PyCharm 5 导入错误

javascript - 有选择地设置 div jQuery 中多个输入的属性

javascript - 在后面的代码中读取时隐藏控制值不正确

javascript - 使模块在 jasmine 通过 Resharper 测试的 Controller 中可用

javascript - 将参数传递给模板?

html - CSS 文本垂直居中对齐