【问题标题】:Remove a created Div删除创建的 Div
【发布时间】:2017-10-03 20:05:10
【问题描述】:

我正在尝试让我的代码使用一个函数新删除一个 div。

JavaScript 可以毫无问题地添加新的新 div。但是删除按钮没有响应。

如何让我的 JavaScript 删除 div。

脚本:

	<script async> // hidden answer for adding new answers jacascript code
			   function clonebutton1 (counter){
				   counter = counter +1;
				   var div = document.createElement('div');
				   div.className = 'container-fluid form-group col-lg-6';
				   div.innerHTML ='<label>Answer:\
			<span id="ansNo">'+counter+'</span>\
			</label> \
			<input class="form-control" id="AnswerClone" name="quizAnswerNew[]" placeholder="Please Enter An Answer......" type="text" value="">\
			<div class="form-group">\
				<label for="select1">Pick a Score For The Answer:</label> \
				<select class="score-choice" id="selectClone" name="selectNew">\
				<option selected value="0">0</option><option value="5">5</option><option>10</option><option>15</option><option>20</option>\
				</select>\
			</div>\
			<div style="margin-bottom:20px;">\
				<label class="btn-bs-file btn btn-sm btn-primary">Add Picture <input name="answerFileNew" type="file"></label>\
			</div><input class="btn btn-primary removeAnswer" id="removeAnswer" type="button" value="Remove Answer">\
		</div>';
	
			document.getElementById('AnswerSectionNew').appendChild(div);
					              div.on("click", function() {// this function removes the parent of the removeAnswer button that is clicked
									$(this).parent().remove();
					  });
			document.getElementById('addAnotherAnswer').setAttribute("onClick","clonebutton1("+counter+")");
	  };
			  
			  
	      
	</script>

谢谢

【问题讨论】:

    标签: javascript append clone getelementbyid removechild


    【解决方案1】:

    您正在将该函数绑定到按钮的 click 事件,但可能尚未创建该 div。所以每次用按钮创建div时都应该重新绑定click事件。

    另一种选择是在创建时(这是在编写 html 时)使用按钮上的 onclick 属性来执行 JavaScript 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 2021-10-21
      相关资源
      最近更新 更多