[英]Jquery: How to get parent div of an element and clone it?
On the click of addField_1 button, I have to clone the container div(id = 'projection') and append it right below it.单击 addField_1 按钮后,我必须克隆容器 div(id = 'projection') 并将其附加在其正下方。
I am doing this in jquery
like this:我在
jquery
这样做:
$('[id^="addField"]').click(() => { var containerDiv = $(this).parent(); console.log(containerDiv.attr('id')); containerDiv.after(containerDiv.clone()); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="row" id="projection" > <select class="form-control" aria-placeholder="Select field"></select> <button type="button" class="btn btn-light" id="addField_1" name="mybutton">+</button> </div>
There is no error when the button is clicked.单击按钮时没有错误。 But the div is not being copied.
但是 div 没有被复制。 I also tried to log the parent div's id.
我还尝试记录父 div 的 id。 It is also undefined.
它也是未定义的。 Please tell me what am I doing wrong.
请告诉我我做错了什么。
Notice that you have used arrow function because of which this
is referring to the window
.请注意,您使用了箭头函数,因此
this
指的是window
。
There are two solutions for it :有两种解决方案:
1. Using event.target
in the arrow function to get the targeted element. 1. 在箭头函数中使用
event.target
获取目标元素。
$('[id^="addField"]').click((event) => { let containerDiv = $(event.target).parent(); console.log(containerDiv.attr('id')); containerDiv.after(containerDiv.clone()); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="row" id="projection" > <select class="form-control" aria-placeholder="Select field"></select> <button type="button" class="btn btn-light" id="addField_1" name="mybutton">+</button> </div>
2. To not use arrow function but anonymous function and use this
: 2. 不使用箭头函数而是使用匿名函数并使用
this
:
$('[id^="addField"]').click(function() { let containerDiv = $(this).parent(); console.log(containerDiv.attr('id')); containerDiv.after(containerDiv.clone()); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="row" id="projection" > <select class="form-control" aria-placeholder="Select field"></select> <button type="button" class="btn btn-light" id="addField_1" name="mybutton">+</button> </div>
With this keyword, you will reference to Window object.使用此关键字,您将引用 Window 对象。
That why you should use something like that:这就是为什么你应该使用类似的东西:
$('[id^="addField"]').on('click', event => {
const parentDiv = $(event.target).closest('.row');
console.log(parentDiv.html());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.