[英]How to use `onclick` inside javascript string literal
Is it possible to use onclick
inside of a string literal? 是否可以在字符串文字中使用
onclick
?
I have a page
view like so: 我有这样的
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;
It's being used in a router like so: 它正在像这样的路由器中使用:
import page from './page.js';
window.onload = () => {
page()
}
which is imported in my index.html
file as a module as <script type="module" src="router.js"></script>
它作为
<script type="module" src="router.js"></script>
作为模块导入到我的index.html
文件中
This works. 这可行。
However, I'd like to avoid document.getElementById('messageCta').onclick
. 但是,我想避免
document.getElementById('messageCta').onclick
。 Is there a way to use the onclick
event instead? 有没有办法使用
onclick
事件呢?
Something like 就像是
const openMessageComposer = () => {
console.log("openMessageComposer")
}
which would exist inside the page
component. 它会存在于
page
组件内部。
You currently have two onclicks: one, in the inline attribute, which tries to reference a global variable named openMessageComposer
but then does nothing with it. 当前,您有两次onclicks:一次,在inline属性中,它尝试引用名为
openMessageComposer
的全局变量,但是openMessageComposer
不执行任何操作。 (your other is your .onclick
) If you want to remove the .onclick
, then just make sure the inline handler invokes the openMessageComposer
function instead: (另一个是您的
.onclick
)如果要删除.onclick
,则只需确保内联处理程序调用 openMessageComposer
函数即可:
onclick="openMessageComposer()"
But inline attributes are generally considered to be pretty poor practice, and can make scripts significantly more difficult to manage, especially in larger codebases - I'd prefer your current method of assigning to the onclick
property of the element. 但是内联属性通常被认为是相当差的做法,并且会使脚本更加难以管理,尤其是在较大的代码库中-我更喜欢您当前分配给元素的
onclick
属性的方法。
If it's the requirement of adding the id
to the appended element that you don't like, then create the element explicitly with createElement
instead, so you have a direct reference to it, without giving it an id
, and assign to its onclick
property: 如果需要将
id
添加到您不喜欢的附加元素上,请改为使用createElement
显式创建该元素,这样就可以直接引用它,而无需为其提供id
,并为其分配onclick
属性:
const page = () => {
const button = document.createElement('button');
button.textContent = 'Message';
button.onclick = openMessageComposer;
document.getElementById('app').appendChild(button);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.