使用javascript中的2个按钮添加和删除文本(条件:使用div id'divResult',控制台日志。)

问题描述 投票:0回答:1

我想制作一个带有2个按钮(添加,删除)的网页。条件是使用div id divResult,控制台日志,并且删除该div后必须保留。它的工作原理几乎是正确的,只是最后一步(删除alinea)无效。您能帮我吗,我该如何解决? :-)

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <title>2 buttons</title>
  <script >

var index = 1;

window.onload = function () {
  document.getElementById('Btn1').onclick = function () {

    var newElement = document.createElement('div');
    newElement.id = 'div' + index++;
    
    var node = document.getElementById('txtElement').value;
    var newNode = document.createTextNode(node);
    
    newElement.appendChild(newNode);

    console.log(newElement);
    document.getElementById('divResult').appendChild(newElement);
  };
  document.getElementById('Btn2').onclick = function () {
		
                var oldDiv = document.getElementById('txtElement')
				var alinea = oldDiv.querySelectorAll('p:last-child')[0]; 
				console.log(alinea + ' wordt verwijderd...');
				
				oldDiv.removeChild(alinea);
				console.log('verwijderd!');
  };
};
  </script>
</head>
<body>
  <p>Type your text in the text box and click on Button</p>
  <input type="text" id="txtElement">
  <button id="Btn1">Add</button>
  <button id="Btn2">Delete</button>
  <div id="divResult"></div>
  <div id="oldDiv"></div>
</body>

</html>
javascript html button add console.log
1个回答
0
投票

我已经尝试了几件事,四处移动东西。我认为它正在做您现在想要的。

	  var index = 1;

	  window.onload = function () {
			document.getElementById('Btn1').onclick = function () {

				 var newElement = document.createElement('div');
				 newElement.id = 'div' + index++;

				 var node = document.getElementById('txtElement').value;
				 var newNode = document.createTextNode(node);

				 newElement.appendChild(newNode);

				 console.log(newElement);
				 document.getElementById('divResult').appendChild(newElement);
			};
			document.getElementById('Btn2').onclick = function () {

				 var oldDiv = document.getElementById('txtElement');
				 var divResult = document.getElementById('divResult');
				 var alinea = divResult.querySelectorAll('div:last-child')[0];
				 console.log(alinea + ' wordt verwijderd...');

				 alinea.remove();
				 // divResult.removeChild(alinea);
				 console.log('verwijderd!');
			};
	  };
<p>Type your text in the text box and click on Button</p>
<input type="text" id="txtElement">
<button id="Btn1">Add</button>
<button id="Btn2">Delete</button>
<div id="divResult"></div>
<div id="oldDiv"></div>
© www.soinside.com 2019 - 2024. All rights reserved.