在特定父母div中重复隐藏div
我在复制DIV并在其自己的父级中显示它有问题。我有几个divs带有相同的重复按钮。但是,该按钮仅在父母div中复制DIV。它不会在其自己的父级内显示DIV。
在我的示例中,我有四个按钮。单击其中一个时,应按下按钮下方显示一个div。但是,它只复制DIV并将其显示在其中一个按钮下方。我在做什么错?
$(document).ready(function() {
$(".addB").click(function() {
$(".newDiv")
.eq(0)
.clone()
.insertAfter(".newDiv:last")
.show();
});
$(document).on('click', '.addB button[type=submit]', function(e) {
e.preventDefault()
var $frm = $(this).closest('.addB');
console.log($frm.serialize());
$.ajax(
$frm.attr('action'), {
method: $frm.attr('method'),
data: $frm.serialize()
}
);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have a problem with duplicating a div and displaying it within it's own parent div. I have several divs with the same duplication button. However, the button only duplicates the div in one of the parent divs. It does not display a div within its own parent div.
In my example I have four buttons. When clicking one of them there should be a div displaying underneath the button you press. However, it only duplicates the div and displays it underneath ONE of the buttons. What am I doing wrong?
https://jsfiddle.net/qer6c5b1/
$(document).ready(function() {
$(".addB").click(function() {
$(".newDiv")
.eq(0)
.clone()
.insertAfter(".newDiv:last")
.show();
});
$(document).on('click', '.addB button[type=submit]', function(e) {
e.preventDefault()
var $frm = $(this).closest('.addB');
console.log($frm.serialize());
$.ajax(
$frm.attr('action'), {
method: $frm.attr('method'),
data: $frm.serialize()
}
);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题归因于您的固定
.newdiv:last
选择器 - 无论单击哪个按钮,这将始终针对相同的元素。要解决此问题,您可以从传递给事件处理程序的事件中单击哪个按钮,然后使用DOM Traversal查找相关的
.newdiv
clone。另请注意,我修改了
parentDiv
类在所有元素中很常见。这是因为增量class
和id
属性是一种反模式,应避免。最后,该逻辑假设每个按钮都在其父母内附加不同的内容。如果每次克隆的内容都是相同的,请克隆单个元素并从DOM中删除重复项,或使用
&lt; template /&gt; < /code>保存要附加的内容。
The issue is due to your fixed
.newDiv:last
selector - this will always target the same element no matter which button is clicked.To fix this you can determine which button was clicked from the Event that's passed to the event handler and then use DOM traversal to find the related
.newDiv
to clone.Also note that I amended the
parentDiv
class to be common amongst all the elements. This is because incrementalclass
andid
attributes are an anti-pattern and should be avoided.Finally, this logic assumes that each button is appending different content from within its parent. If the content that's cloned is identical each time, clone a single element and remove the duplicates from the DOM, or use a
<template />
to hold the content to be appended.