簡體   English   中英

如何使用javascript中的鼠標懸停事件刪除我在javascript中創建的DOM節點?

[英]How do I remove DOM nodes that I created in javascript using mouseover events in javascript?

所以 HTML 顯示了一個區域,其中有 100 個隨機位置的小框。 我使用 javascript 來制作小盒子。 HTML 中還有一個按鈕,我在 js 中編寫了該按鈕,每次單擊時都會生成一百多個小框。 我的問題是我希望每次將鼠標懸停在每個小框上時都能讓它消失,最好使用“this”命令來做到這一點。 我做錯了什么,還是javascript在創建新的HTML元素后無法與它們交互?

這是我的代碼:

 window.onload = function(){
 createBoxes();
 $("myButton").observe("click", createBoxes);
 var divvy = $("container");
 var pars = divvy.getElementsByTagName("p")
 pars.onmouseover = destroyBoxes;

}
function destroyBoxes (event){
var divvy = $("container");
var pars = divvy.getElementsByTagName("p")
if (event.type == "mouseover")   {
pars.removeChild(This);
}

}



function createBoxes()
{
var colors = ["red", "green", "grey", "blue", "orange", "yellow"];
for (i=0;i<=99;i++){
var newP = document.createElement("p");
var top = Math.floor( Math.random() *400 ) + "px";
var left = Math.floor( Math.random() *400 ) + "px";
newP.style.top  = top;
newP.style.left  = left;
newP.style.backgroundColor = colors[ Math.floor( Math.random() *6 )];
$("container").appendChild(newP);
      var divvy = $("container");
      var pars = divvy.getElementsByTagName("p")
      pars.onmouseover = destroyBoxes;
    }
    }

“嘗試在destroyBoxes()函數中使用event.target而不是This 。”

話雖這么說......在自己發現解決方案方面做得很好!

如果有興趣,這是我使用 jQuery 函數的解決方案。

 window.onload = function() { createBoxes(); $(".myButton").on("click", createBoxes); // Use class selector //Find all `p`s in `container` //$pars.on('hover', destroyBox); } function destroyBox(event) { var $target = $(event.target); // The 'if' statement is redundant. Only run the function if wanted. //if (event.type == "mouseover") { $target.remove(); //} } function createBoxes() { var colors = ["red", "green", "grey", "blue", "orange", "yellow"]; var newPs = []; for (i = 0; i < 100; i++) { var top = Math.floor(Math.random() * 400), left = Math.floor(Math.random() * 400), color = colors[Math.floor(Math.random() * 6)]; var $newP = $('<p></p>').css({top: top, left: left, backgroundColor: color}); newPs.push($newP); } var $container = $(".container").append(newPs); // Use class selector $container.find('p').on('mouseover', destroyBox); }
 .container { position: relative; } p { position: absolute; width: 10px; height: 10px; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div> <button type="button" class="myButton">Click for more!</button> </div> <div class="container"></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM