克隆元素时如何避免重复的id?

时间:2014-09-18 16:10:36

标签: javascript jquery

使用jquery clone方法处理重复id的好策略是什么?例如,我需要克隆一个未指定次数的按钮。哪个是生成唯一ID并跟踪它的最佳方法?

<div id="button-pool">
    <button id="bt1" class="return">Button</button>
</div>

$(document).ready(function(){
    $("#bt1").click(function(){
       var newButton = $(this).clone();
        $("#button-pool").append(newButton);
    });
});

http://jsfiddle.net/uv95nzrk/

6 个答案:

答案 0 :(得分:3)

您可以使用Attribute StartsWith Selector查看已存在多少具有相同ID命名样式的按钮:

"button[id^='bt']"

并将其增加1

$(document).ready(function(){
    $("#bt1").click(function(){
        var idcount = $("button[id^='bt']").length;
        
        var newButton = $(this).clone();
        newButton.attr("id", "bt" + (idcount + 1));
        $("#button-pool").append(newButton);
    });
});
.return{
    background-color: yellow;
}
#bt1{
    border: 2px solid navy;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="button-pool">
    <button id="bt1" class="return">Button</button>
</div>

答案 1 :(得分:2)

利用Classes来实现这是一个更好的策略,使用生成的ID膨胀你的DOM并不是一个好主意。 (糟糕的设计实践)

<div id="button-pool">
    <button class="btns" custom-attr='1' class="return">Button</button>
</div>

$(document).ready(function(){
    $(".btns").click(function(){
       var newButton = $(this).clone();
        newButton.attr('custom-attr', parseInt(newButton.attr('custom-attr'))+1);
        $("#button-pool").append(newButton);
    });
});

您还可以使用自定义属性来跟踪按钮,以便它们彼此保持唯一,但它们并不需要具有ID

答案 2 :(得分:0)

您可以使用简单的计数器,并将其附加到按钮ID。此计数器应位于封闭内,不会干扰页面中的其余脚本;

$(document).ready(function(){
  var btnId = 1; // This is a safe place, inside a closure (function body).
  $("#bt1").click(function(){
      var newButton = $(this).clone();
      newButton.attr('id','btn' + btnId);
      btnId++; // Increment after creating each new button
      $("#button-pool").append(newButton);
  });
});

您也可以创建没有ID的按钮,除非您确实需要它们。你为什么需要跟踪它们?

答案 3 :(得分:0)

这样的事情应该有效

var count = 0;
$("#bt1").click(function(){
   var newButton = $(this).clone();
    newButton.attr("id", "bt"+count);
    $("#button-pool").append(newButton);
    count++;
});

答案 4 :(得分:0)

$(document).ready(function(){
    $("body").on('click','#bt1',function(){
       var newButton = $(this).clone();
        $("#button-pool").append(newButton);
    });
});

答案 5 :(得分:0)

简单回答是使用class代替id

相关问题