【问题标题】:Not able to call a function using document.getElementById('password').addEventListener() with a webpack & ES6 setup无法使用带有 webpack 和 ES6 设置的 document.getElementById('password').addEventListener() 调用函数
【发布时间】:2019-03-18 21:30:22
【问题描述】:

我正在使用 webpackES6 类。我试图在 input#password 上调用 'onblur' 函数,但它不起作用。它既不会抛出任何错误,也不会调用回调函数。如果我尝试使用 console.log(document.getElementById('password')) 在 eventListener 之外找到 input#password,那么它会给我 input#password 作为 DOM 对象。我不知道我哪里错了。以下是我的代码:

index.html

    <head>
      <script src="./bundle.js"></script>
    </head>
    <body>
       <input id="password" type="password" placeholder="Please enter your password" autofocus="autofocus">
    </body>

webpack-config.js

const path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist')
    }
};

index.js

import { Password } from './app/main';

document.getElementById('password').addEventListener('onblur', () => {
    console.log('im here');
    var initPwd = new Password();
    initPwd.init();
})

main.js

class Password {
    init() {
        console.log('I am inside init.')
    }
}

export { Password }

请帮忙!

【问题讨论】:

    标签: javascript webpack ecmascript-6 addeventlistener es6-class


    【解决方案1】:
    document.getElementById('password').addEventListener('onblur', () => {
    

    =>

    document.getElementById('password').addEventListener('blur', () => {
    

    onblur 将与element.onblur = function() {} 一起使用,因此当您使用addEventListener 接口时,您不应在事件名称中写入on

    【讨论】:

    • 感谢您的解决方案。
    【解决方案2】:

    问题在于事件名称blur,而您可以通过分配给元素的onblur 属性来分配处理程序。它们不一样,这可能有点令人困惑。

    当您通过分配给属性来附加侦听器时,您使用&lt;element&gt;.on&lt;eventName&gt; 语法,例如:

    element.onclick = () => ...
    element.onblur = () => ...
    

    当您使用addEventListener 时,您只需使用纯事件名称:

    element.addEventListener('click', () => ...
    element.addEventListener('blur', () => ...
    

    所以,改成:

    document.getElementById('password').addEventListener('blur', () => {
    

    document.getElementById('password').addEventListener('blur', () => {
      console.log('blur');
    });
    &lt;input id="password" type="password" placeholder="Please enter your password" autofocus="autofocus"&gt;

    【讨论】:

    • 感谢您的解决方案。
    • 当某个答案解决了您的问题时,请考虑投票并将其标记为已接受,以表明问题已解决:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    相关资源
    最近更新 更多