简体   繁体   中英

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

why does that render prevent the firing or why would anything prevent it from firing (more than once)?

setup: bundling js from deno

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. You should only overwrite a part of the form by making a div or other element inside the form.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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