如何在javascript字符串文字中使用`onclick`

问题描述 投票:0回答:1

是否可以在字符串文字中使用onclick

我有这样的page视图:

const page = () => {
  const htmlOutput = `
    <button
      onclick="openMessageComposer"
      id="messageCta">Message</button> // Using the id works
  `;
  document.getElementById('app').innerHTML += htmlOutput;
  document.getElementById('messageCta').onclick = () => {
    console.log("openMessageComposer")
  }
}

export default page;

它被用在像这样的路由器中:

import page from './page.js';

window.onload = () => {
  page()
}

它作为index.html模块导入我的<script type="module" src="router.js"></script>文件中

这有效。

但是,我想避免使用document.getElementById('messageCta').onclick。有没有办法使用onclick事件?

就像是

const openMessageComposer = () => {
  console.log("openMessageComposer")
}

这将存在于page组件内。

javascript module onclick string-literals
1个回答
1
投票

您目前有两个onclicks:一个在inline属性中,它试图引用一个名为openMessageComposer的全局变量,但后来对它没有任何作用。 (你的另一个是你的.onclick)如果你想删除.onclick,那么只需确保内联处理程序调用openMessageComposer函数:

onclick="openMessageComposer()"

但内联属性通常被认为是相当差的实践,并且可能使脚本更难以管理,尤其是在更大的代码库中 - 我更喜欢您当前的方法分配元素的onclick属性。

如果需要将id添加到您不喜欢的附加元素,则使用createElement显式创建元素,因此您可以直接引用它,而不给它一个id,并赋值给它的onclick属性:

const page = () => {
  const button = document.createElement('button');
  button.textContent = 'Message';
  button.onclick = openMessageComposer;
  document.getElementById('app').appendChild(button);
};
© www.soinside.com 2019 - 2024. All rights reserved.