简体   繁体   中英

i have to click twice, why? (JavaScript onclick event handler)

i am new to JavaScript and web development and it is the first time i see this kind of bugs. it is a very basic example, i have two divs- left and right- the left one has five images and the right one is empty , i have also two buttons copy and delete, each has an onclick event handler. the Copy button copies the entire left node (div) and appends it to the right div , the delete button should delete the last image in the right div and it does, the thing is i have to click twice on Delete button to delete one image so i have to click 10 times to delete the entire set. why this happens? what should i do to make the Delete button deletes an image by just clicking once ?

this is my entire code , tested on Microsoft Edge and Google chrome and i got the same result.

 var theLeftSide = document.getElementById("leftSide"); var theRightSide = document.getElementById("rightSide"); function Copy() { copy = theLeftSide.cloneNode(true); theRightSide.appendChild(copy); } function Delete() { copy.removeChild(copy.lastChild); } 
 div { position: absolute; width: 670px; height: 520px; background: red } #rightSide { position: absolute; left: 670px; border-left: 1px solid black; background: black } 
 <input type="button" value="Copy" onclick="Copy()"> <input type="button" value="delete" id="btn" onclick="Delete()"> <div id="leftSide" style="width:400px"> <img src="smile.png" /> <img src="smile.png" /> <img src="smile.png" /> <img src="smile.png" /> <img src="smile.png" /> </div> <div id="rightSide"> </div> 

Most browsers instert by default an empty text node between each element of your page, your code is deleting one empty node for every img, that's why it seems to work half of the times.

Try this:

function Delete(){
  var imgs = document.querySelectorAll('.rightSide img');
  copy.removeChild(imgs[imgs.length-1]);
}

You're removing text nodes as well as elements. What you really want is copy.removeChild(copy.lastElementChild);

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