单击主体内的按钮时,如何从主体中停止事件?

How can i stop an event from the body, when clicking a button inside the body?

所以我想在单击正文时创建按钮,但是当我单击该正文中的按钮时,我不想创建另一个按钮。那么我应该如何处理呢?我试过停止传播但没有用



           /*  var body = document.getElementsByTagName("body")[0];*/

           document.body.onclick = function(event) {
                   var x = event.clientX;
                   var y = event.clientY;
                   var btn = document.createElement("button");
                   btn.style.position = "absolute";
                   btn.style.left = x + "px";
                   btn.style.top = y + "px";
                   btn.innerHTML = "click me";
                   document.body.appendChild(btn);
                   btn.className = "buton";
                   event.stopPropagation;
                   var butoane = document.getElementsByClassName("buton");
                   for (let i = 0; i < butoane.length; i++) {
                       butoane[i].onclick = function() {
                           alert("ai apasat butonul" + (i + 1));

                       }

                   }
               }

event.stopPropagation 是一个函数,您需要调用它,类似于 event.stopPropagation() 但无论如何,这不会满足您的需求。 您可以忽略对您创建的按钮的点击,如下所示:

document.body.onclick = function(event) {
  if (event.target.classList.contains('buton')) {
    return;
  }
  var x = event.clientX;
  var y = event.clientY;
  var btn = document.createElement("button");
  btn.style.position = "absolute";
  btn.style.left = x + "px";
  btn.style.top = y + "px";
  btn.innerHTML = "click me";
  document.body.appendChild(btn);
  btn.className = "buton";
  event.stopPropagation;
  var butoane = document.getElementsByClassName("buton");
  for (let i = 0; i < butoane.length; i++) {
    butoane[i].onclick = function() {
      alert("ai apasat butonul" + (i + 1));

    }

  }
}
<button>Button</button>

这是为了检查点击的元素是否有 buton class 如果有,return(不要 运行 生成的代码一个按钮)。

此外,您可以改进这一点,而不是转到您创建的每个按钮来重置它的 onclick 侦听器,您可以这样做:

btn.onclick = function() {
  alert("ai apasat butonul" + butoane.length);
}

尽量不要使用 .onclick 更好地使用 .addEventListener(event, handle) 然后如果你需要你可以删除事件监听器

你写错了.stopPropagation()

let ev = document.body.addEventListener("click", bodyclick)
let butoane = ""

function bodyclick(event){
   let x = event.clientX;
   let y = event.clientY;
   let btn = document.createElement("button");
   btn.style.position = "absolute";
   btn.style.left = x + "px";
   btn.style.top = y + "px";
   btn.innerHTML = "click me";
   document.body.appendChild(btn);
   btn.className = "button";
   event.stopPropagation();
   butoane = document.querySelectorAll(".button");
  butoane[butoane.length - 1].addEventListener("click", buttonclick) // add event only for just added button, not for all buttons again
}

function buttonclick(ev){
  ev.stopPropagation()
  alert("press button ", ev.currentTarget)
}
body{
width: 100%;
height: 100vh;
}