简体   繁体   English

如何将 DOMContentloaded 事件侦听器添加到 nextJS 中的文档?

[英]How do I add the DOMContentloaded event listener to the document in nextJS?

I'm trying to add an html code snippet to my nextjs project.我正在尝试将 html 代码片段添加到我的 nextjs 项目中。 The code snippet contains external script which has a createButton function.代码片段包含具有 createButton function 的外部脚本。

<div id="examplebtn"></div>
  <script type="text/javascript">
    //<![CDATA[
    document.addEventListener('DOMContentLoaded', function () {
      createButton('Name', 'Phone');
    });
    //]]>
  </script>
  <script src="https://example.com.na/js/example.js"></script>

The createButton function renders a button identified by the id (examplebtn in this case) and in a native html document it works fine. createButton function 呈现一个由 id 标识的按钮(在本例中为 examplebtn),在本机 html 文档中它工作正常。 However, in nextjs I am unable to add an event listener to the DOMContentLoaded event as is shown in the script, for it to run the function once the DOM has been loaded.但是,在 nextjs 中,我无法如脚本所示向 DOMContentLoaded 事件添加事件侦听器,因为它在加载 DOM 后运行 function。 I have tried using Next/Script, useEffect hooks, native html tags all to no avail.我尝试使用 Next/Script、useEffect 挂钩、原生 html 标签都无济于事。 How can I add the DOMContentLoaded event listener to the jsx component before the document is completely loaded so the function can run at the appropriate time?如何在文档完全加载之前将 DOMContentLoaded 事件侦听器添加到 jsx 组件,以便 function 可以在适当的时间运行? Thank you in advance for your kind assistance.提前感谢您的帮助。

{EDIT} I'm adding the final code of createButton for more clarity. {EDIT} 为了更清晰,我添加了 createButton 的最终代码。 It's been edited as I can't release the code due to contractual obligations, however it should prove helpful.由于合同义务,我无法发布代码,因此对其进行了编辑,但它应该会有所帮助。

window
  .ButtonComponent({
    params,
    onPay: function (v, vn, a, r, e) {
      c = customFunct(moreParams);
      PopupComponent({
        params,
        onCancel: function () {
          console.log('called onCancel');
          // stuff here
        },
        onSubmit: function (r) {
          // stuff here
        },
      }).render('body');
    },
  })
  .render('#examplebtn');
    <div id="examplebtn"></div>
  {    
    document.addEventListener('DOMContentLoaded', function () {
      createButton('Name', 'Phone');
    });  
  }

just use block and write whatever the script you want to只需使用块并编写您想要的任何脚本

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

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