我正在尝试使jQuery做到这一点:
当我单击按钮时,它会选择next()
元素并将其克隆。如果再次单击该按钮,它将选择下一个元素的下一个元素并将其克隆,依此类推...
长故事简短内容...我单击一次它克隆了“ 2”,再次单击它克隆了“ 3”,依此类推...
出了什么问题,我该如何解决?
var x = $(".show");
$(".button").click(function() {
$(".first").next().clone(true, true).appendTo(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="button">CLICK ME</button>
<ul style="position:relative; top:100px;">
<div class="test">
<div class=first>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</div>
<div class="show"></div>
答案 0 :(得分:1)
我会做这样的事情:
var x = $(".show");
var count = 0;
$(".button").click(function() {
var element = $(".first");
count++;
for (var i = 0; i < count; i++) {
element = $(element).next();
}
$(element).clone(true, true).appendTo(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="button">CLICK ME</button>
<ul>
<div class="test">
<div class=first>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</div>
<div class="show"></div>
答案 1 :(得分:1)
此演示是一个可重用的函数(只记得在函数外部声明间隔(var i = 0
)。由于您没有提及是否要克隆给定节点数,所以我添加了一个确认一旦达到该限制。
var i = 0;
$(".button").on('click', function() {
dupeNode('.hide li', '.show');
});
function dupeNode(selector, TO) {
if (i > $(selector).length - 1) {
return msg.call(this);
}
$(selector).eq(i).clone(true, true).appendTo($(TO));
i++;
}
function msg() {
var m = confirm(`
Last item was already cloned.
[OK] to at the beginning or
[Cancel] to quit.`);
var x = m ? i = 0 : false;
return x;
}
ul {
list-style: none;
}
li {
display: inline-table;
}
li::after {
content: "\2c\a0";
}
.show {
visibility: visible
}
.hide {
visibility: hidden
}
<main class="container">
<button class="button">CLICK ME</button>
<ul class='show'></ul>
<ul class="hide">
<li class=first>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>