Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

html - How trigger events on elements created afterwards other events in Javascript?

I have replicated windows calculator. I am stuck with the "memory tab".

I need to create click events on the three buttons: MC M+ M- as below (top right of the screen). enter image description here

The problem is that these buttons (and all the elements around) are created afterwards every time i click "MS" on the main calculator (left of the screen, above main buttons).

function addMemoryValue(){
  const uls = document.createElement("ul");
  const lis = document.createElement("li");
  const h2s = document.createElement("h2");
  h2s.textContent = Number(display.textContent);
  const h3s = document.createElement("h3");

  uls.appendChild(lis);
  lis.appendChild(h2s);
  h2s.appendChild(h3s);

  let valueBtn = ["MC", "M+", "M-"];

  valueBtn.forEach((element) => {
  const memoryBtn = document.createElement("button");
  memoryBtn.setAttribute("value", element);
  memoryBtn.textContent = element;
  const memorySpn = document.createElement("span");
  memorySpn.appendChild(memoryBtn);
  memoryBtn.classList.add("btnsave");
  h3s.appendChild(memorySpn);

  const buttonTest = document.getElementsByClassName("btnsave");
  console.log(buttonTest.textContent);
  })

I want to iterate theses buttons and create if statements according to the textContent but I am not sure how to target the buttons since they don't exist yet.

If for example I try the following:

const buttonTest = document.getElementsByClassName("btnsave");
console.log(buttonTest.textContent);

I get "undifined" regardless wheteher console.log is inside or outside the function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can add click event handlers directly where you create the buttons like this:

var clickHandler = function() {
    console.log("button clicked");
};

var button = document.createElement("button");
button.textContent = "test";
button.addEventListener("click", clickHandler);

document.getElementById("container").appendChild(button);
<div id="container">

</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...