简体   繁体   English

如何在 es6 模块上调用 function

[英]How can I call a function on es6 module

I have tried so many things but it hasn't worked.我已经尝试了很多东西,但它没有奏效。 I am not using react in this project so not sure how i can call the shoeAlert() function when the button is clicked.我没有在这个项目中使用反应,所以不确定单击按钮时如何调用 shoeAlert() function。 PLEASE HELP!!请帮忙!!

import '../Nav/nav.styles.scss';

const Nav = () =>  {
    
    function showAlert(e) {
        e.preventDefault();
        console.log("I'm an alert");
    };
   return ( `
        <div class='nav'>
            <div>
                <p>Logo</p>
                <button id='btn' onclick="{this.showAlert}"> Click Me</button>
            </div>
        </div> `);
} 
 
export { Nav };

Instead of returning an HTML string, create and return the parent .nav element.与其返回 HTML 字符串,不如创建并返回父.nav元素。 You can attach the listener to the inner button before returning.您可以在返回之前将侦听器附加到内部按钮。

const Nav = () => {
    function showAlert(e) {
        e.preventDefault();
        console.log("I'm an alert");
    };
    const nav = document.createElement('div');
    nav.className = 'nav';
    nav.innerHTML = `
        <div>
            <p>Logo</p>
            <button id='btn'> Click Me</button>
        </div>
    `;
    nav.querySelector('button').addEventListener('click', showAlert);
    return nav;
};

Working snippet:工作片段:

 const Nav = () => { function showAlert(e) { e.preventDefault(); console.log("I'm an alert"); }; const nav = document.createElement('div'); nav.className = 'nav'; nav.innerHTML = ` <div> <p>Logo</p> <button id='btn'> Click Me</button> </div> `; nav.querySelector('button').addEventListener('click', showAlert); return nav; }; const nav = Nav(); document.body.appendChild(nav);

showAlert is also a standalone identifier, not a property of any instance, so you don't want this.showAlert , you just want showAlert . showAlert也是一个独立的标识符,而不是任何实例的属性,所以你不需要this.showAlert ,你只需要showAlert

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

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