简体   繁体   English

单击侦听器仅触发一次,其中包含渲染方法

[英]click listener only fires once with a render method inside it

i have a click listener on a button that resets the innerhtml of a div with a render method.我在一个按钮上有一个点击监听器,它使用渲染方法重置 div 的 innerhtml。 taking out the render the click listener fires every time i click, with the render in there it doesn't.每次单击时,单击侦听器都会触发渲染,而其中的渲染则不会。

i've tried removing the html tagging and all external function calls, still same problem我试过删除 html 标记和所有外部 function 调用,仍然是同样的问题

why does that render prevent the firing or why would anything prevent it from firing (more than once)?为什么渲染会阻止射击,或者为什么会有任何东西阻止它射击(不止一次)?

setup: bundling js from deno设置:从 deno 捆绑 js

const myTemplate = (formData: HCPConfig) => {
  return html` ... `;}

//byId just returns an el or throws an error
const rootEl = byId("form"); 
function render(el: Element, content: string) {
  el.innerHTML = content;
 
}
render(rootEl, myTemplate(formData)); //this renders fine on page load
const action = byId("submitty");

action.addEventListener("click", function (e: Event) {
  console.log(e);
  //this prevents the event listener from firing more than once
  render(rootEl, myTemplate(formData)); 
 
});

If the #submitty button is inside the #form element, you are overwriting the button and all the other contents of #form with the content.如果#submitty按钮位于#form元素内,则您将使用该内容覆盖按钮和#form的所有其他内容。 You should only overwrite a part of the form by making a div or other element inside the form.您应该只通过在表单中创建 div 或其他元素来覆盖表单的一部分。

I was able to fix this by putting the button that has the clicklistener attached to it outside of the the item getting re-rendered.我可以通过将附加了 clicklistener 的按钮放在重新渲染的项目之外来解决这个问题。

const ssFormCtl = (content = "Submit"): string => {
  return html`<button type="button" class="btn btn-primary" id="submitty">
    ${content}
  </button>`;
};
const myTemplate = (formData: HCPConfig) => {
  return html` ... `;}

//byId just returns an el or throws an error
const rootEl = byId("form"); 
const ctlEl = byId("ssFormCtl");
function render(el: Element, content: string) {
  el.innerHTML = content;
 
}
render(rootEl, myTemplate(formData)); 
render(ctlEl, ssFormCtl());
const action = byId("submitty");

action.addEventListener("click", function (e: Event) {
  console.log(e);
  render(rootEl, myTemplate(formData)); 
 
});

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

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