Setting HTML Button`onclick` in template literal

耗尽温柔 提交于 2020-04-08 13:23:46

问题


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)))
  })

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.

Any ideas?


回答1:


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.

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.


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).




回答2:


const markUp = `
    <button onclick="myFunction()">Click me</button>
`;

document.body.innerHTML = markUp;

window.myFunction = () => {
    console.log('Button clicked');
};


来源:https://stackoverflow.com/questions/43298962/setting-html-buttononclick-in-template-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!