在模板文字中设置HTML Button`onclick` [英] Setting HTML Button`onclick` in template literal
问题描述
我有一个html模板,我正在使用它的模板文字.该功能如下图所示
I have an html template that i'm using template literals for. The function looks like the below
// postCreator.js
export const blogPostMaker = ({ title, content, address, id }, deletePost) => {
const innerHtml = `
<blog-post>
<h1 class='title'>${title}</h1>
<p class='content'>${content}</p>
<p class='address'>${address}</p>
<button onclick='${() => deletePost(id)}'>Delete</button>
</blog-post>
`
return innerHtml
}
//Blog.js
postHelper.getSeriesOfPosts(10)
.then(resp => {
resp.forEach(post => (blogDiv.innerHTML += blogPostMaker(post, postHelper.deletePost)))
})
我不知道如何使onclick发挥作用.我尝试将Blog.js
中的anon函数传递给postCreator
,也没有运气.
What I can't figure out is how to get the onclick to work. I've tried passing in an anon function in Blog.js
to the postCreator
as well with no luck.
有什么想法吗?
推荐答案
如果您不想在全局范围内公开事件回调,则应使用addEventListener()
将其附加到代码的JS部分:
If you don't want to expose the event callback globally, you should attach it in the JS part of the code with addEventListener()
:
// postCreator.js
export const blogPostMaker = ({ title, content, address, id }) =>
`
<blog-post id='${id}'>
<h1 class='title'>${title}</h1>
<p class='content'>${content}</p>
<p class='address'>${address}</p>
<button>Delete</button>
</blog-post>
`
//Blog.js
postHelper.getSeriesOfPosts(10).then(resp => {
resp.forEach(post => {
blogDiv.innerHTML += blogPostMaker(post)
blogDiv.querySelector(`blog-post[id="${post.id}"] > button`)
.addEventListener('click', () => postHelper.deletePost(post.id))
})
注意:这不是最有效的方法,但可以保留文件结构.
Note: it's not the most efficient way to do it but it keeps your file structure.
相反,我将直接使用createElement()
创建<button>
,然后使用appendChild()
将其添加到DOM中,或者我将使用DocumentFragment或<template>
来避免在所有blogDiv
.
Instead I would create the <button>
directly with createElement()
and then add it to DOM with appendChild()
, or I would use a DocumentFragment or a <template>
in order to avoid querySelector()
on all of the blogDiv
.
如果您绝对希望使用内联JS而不公开帮助程序,则需要将其定义为组件(例如,自定义元素).
If you absolutely want to use inline JS without exposing the helper you'll need to define your as a component (for example a Custom Element).
这篇关于在模板文字中设置HTML Button`onclick`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!