clone - 如何使用克隆的 jQuery 对象为 div 内容中的每个 id 属性添加增量值

标签 clone jquery jquery-click-event

很难弄清楚如何使用克隆的 jQuery 对象为 div 内容中的每个 id 属性添加增量值。

http://jsfiddle.net/hvK8d/

====================== HTML======================

    <div class="upload-file-container">
  <div class="uploadFile left clearfix">
    <input type="file" id="FileUpload1">
    <table id="RadioButtonList1">
      <tbody>
        <tr>
          <td><input type="radio" value="Resume"  id="RadioButtonList1_1">
            <label for="RadioButtonList1_1">Resume</label></td>
          <td><input type="radio" value="Letter of Recommendation"  id="RadioButtonList1_2">
            <label for="RadioButtonList1_2">Letter of Recommendation</label></td>
          <td><input type="radio" value="Other"  id="RadioButtonList1_3">
            <label for="RadioButtonList1_3">Other</label></td>
        </tr>
      </tbody>
    </table>
  </div>
  <a href="javascript:;" class="remove left">Remove</a> </div>
<div class=""><a class="plus" href="javascript:;">plus one</a></div>

====================== JQUERY ====================

    //Cloning upload file control
$('.remove').live('click', function () {
    if (confirm("Are you sure you wish to remove this item?")) {
        $(this).parent().slideUp('fast', function () {
            $(this).remove();
        });
    }
    return false;
});

$('.plus').click(function () {
    console.log('cloning');
    var divCloned = $('.upload-file-container:first').clone();
    divCloned.hide().insertAfter('.upload-file-container:last').slideDown('fast');
    return false;
});

最佳答案

为了完整起见,我将在这里放置一个使用"template"的小解决方案。

隐藏模板的类:

.upload-file-container.template {
  display: none;
}  ​

一个用于替换的小函数:

$.fn.template = function(variables) {
  return this.each(function() {
    this.innerHTML = this.innerHTML.replace(/{{(.+)}}/g, function(match, variable) {
      return variables[variable];
    });
    return this;
  });
};

模板:

<div class="upload-file-container template">
  <div class="uploadFile left clearfix">
    <input type="file" id="FileUpload{{id}}">
    <table id="RadioButtonList{{id}}"><tbody>
      <tr>
        <td>
          <input type="radio" value="Resume"  id="RadioButtonList{{id}}_1">
          <label for="RadioButtonList{{id}}_1">Resume</label>
        </td>
      </tr>
    </tbody></table>
  </div>
</div>

用法:

var count = 0;

var divCloned = $(".upload-file-container.template")
  .clone()
  .removeClass("template")
  .template({
    id: count++
  });

关于clone - 如何使用克隆的 jQuery 对象为 div 内容中的每个 id 属性添加增量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11616897/

相关文章:

git - 克隆 git 存储库时如何自动保留别名?

javascript - 如何在 jQuery 中解析这个无效的 JSON 字符串?

jquery - 简单的数字选择游戏(jQuery)

javascript - FullCalendar dayClick js事件没有分离

javascript - 在 tbody 中的每个 td 上引发 jQuery 单击事件

jquery - 克隆对象中的清除文本字段值

Git 克隆错误 : RPC failed; result=56, HTTP 代码 = 200

jquery 在列表中按索引查找

javascript - 有没有任何事件/方式我们可以知道文件何时完成下载?

javascript - 如何在深度复制时深度复制闭包对象(私有(private)对象)