[英]How to destroy a dynamically created DOM element using jquery?
I am creating a dynamic span inside a span with some form elements and creating button with data-id inside the same dynamically by jquery append in span #add_more. 我在一个带有一些表单元素的span中创建一个动态span,并在span #add_more中通过jquery append动态创建具有data-id的按钮。 I want to remove that particular span when button of that span is clicked.
我想在单击该范围的按钮时删除该特定范围。
Step1. 第1步。
<input type="button" value="Add More" id="more_size">
<span id="add_more"></span>
2.Clicked on Add More button :- 2.点击添加更多按钮: -
<input type="button" value="Add More" id="more_size">
<span id="add_more">
<span id="1001"><input type="text" name="price[]">
<button data-id="1001" type="button">X</button></span>
</span>
3.When clicked on button with id 1001 span with id 1001 should removed using jquery remove(). 3.当使用jquery remove()删除id为1001 span且id为1001的按钮时,应将其删除。
<input type="button" value="Add More" id="more_size">
<span id="add_more"></span>
I am new to stack overflow. 我是堆栈溢出的新手。 This is the best way I can explain my problem.
这是我解释问题的最好方法。
use like this: 使用这样:
function removeSpan(spanId) {
$("#"+spanId).remove();
}
call removeSpan
using spanid
. 调用
removeSpan
使用spanid
。
to pass id you can do like this: 传递id你可以这样做:
$('button').on('click',function(){
id = $(this).data('id');// since your data-id and span id are same
removeSpan(id);
});
or at the time of creation it self you can add the function and pass the id which you have assigned. 或者在创建时,您可以添加该功能并传递您指定的ID。
have a common class on button get data-id of the button clicked... 按钮上有一个公共类获取点击按钮的数据ID ...
<span id="add_more">
<span id="1001"><input type="text" name="price[]">
<button data-id="1001" type="button" class='remove_class'>X</button></span>
</span>
add click event listener to that button using it class (remove_class). 使用它(remove_class)将click事件监听器添加到该按钮。
$(document).on('click','.remove_class',function(){
id = $(this).data('id');
$('#'+id).remove();
});
you can add any number span. 你可以添加任何数字跨度。 using class get current clicked button very easy.
使用类获取当前单击按钮非常容易。
You can simply use the prev()
method: 您只需使用
prev()
方法:
$("#add_more").on("click", "button", function() {
$(this).prev().remove();
});
If you want to remove the button as well, you can use addBack()
: 如果你想删除按钮,你可以使用
addBack()
:
$("#add_more").on("click", "button", function() {
$(this).prev().addBack().remove();
});
I don't suggest manually generating id
's, data-*
attributes etc for this purpose ( If above mentioned is the sole purpose of generating them ), often times you can avoid doing so using a common class and proper methods. 我不建议为此目的手动生成
id
, data-*
属性等( 如果上面提到的是生成它们的唯一目的 ),通常你可以避免使用公共类和适当的方法这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.