附加到(); jquery点击按钮后添加div

appendTo (); jquery add div after the button clicked

我正在克隆 div 并将其添加到末尾 ( appendTo(); ) 我希望复制的 div 在单击按钮后立即附加。截至目前,它正在末尾添加 divs。

有什么解决办法吗?

我的fiddle: http://jsfiddle.net/kgm50e43/15/

这就是 .appendTo 方法的作用。您可以改用 .insertAfter 方法:

// cache the target element
var $parent = $(this).closest(".clonedInput");
// clone the target element 
// and insert the cloned object after the target element 
$parent.clone().insertAfter($parent);

请注意,我使用了 closest 方法而不是 parents 方法,因为您只想 select first/closest 匹配的父元素。 parents是贪心法

您可以使用方法 .after() .insertAfter()。请检查下面的代码段。

//Clone js
var count = 1;
function clone(){
  if (count < 5) {
    var newOne = $(this).closest(".clonedInput").clone(true);
    newOne.find('button.clone').css({'background':'#'+Math.random().toString(16).slice(-6)});
    //background just to show where it landed
    newOne.insertAfter($(this).closest(".clonedInput"));
    count++;
  } 
}
$(".Counter_Play").on("click", 'button.clone', clone);
.al_icons,.clonedInput,.main_icoset{position:relative;overflow:hidden}.clone{display:block;background-color:red;padding:10px}.clonedInput{margin-top:30px;background:#f5f5f5}.IconTest{background:green;width:100px;height:30px;text-align:center;margin-bottom:20px}.main_icoset{width:100%;height:30px}.al_icons{width:34px;height:20px;background-color:#263238;color:#fff;font-size:7px;line-height:22px;text-align:center;float:left;margin-right:2px;display:none;margin-top:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
show hide icons from selected dropdown within the same div. 
<div class="Counter_Play">
  <div class="col s12 l12 m12 First_sec clonedInput">
    Attach only aftter this if this button pressed
    <div class="col s2 m2 l2">
      <button class="clone btn-floating btn-small waves-effect waves-light red counter_start_btn" >
        <i class="material-icons">Duplicate</i>
      </button>
    </div>
  </div>
</div>

简短的回答是使用 .insertAfter 而不是 appendTo,尽管您提供的 fiddle 存在几个问题。

最值得注意的问题是您注册了重复的点击操作。在你的 html 和 JS 中。

<button class="clone btn-floating btn-small waves-effect waves-light red counter_start_btn" onclick="clone();">

$("button.clone").on("click", clone);

欢迎研究我修改的最关键点:

http://jsfiddle.net/thomasmars/kgm50e43/17/