首頁 web前端 js教程 利用 jQuery Clone進行複製操作

利用 jQuery Clone進行複製操作

May 14, 2018 pm 02:47 PM
clone jquery 使用 複製 進行

最近客串了一把前端,有行复制的功能用 jQuery 来实现了。感觉比以前原生js用 CreateElement 要简单多了,但还是遇到了一些陷阱比如IE7的bug,这里记录下来。先看看 table 的样子:这里3行是一组,按下"Copy"连值复制,按下"Add"只增加行不复制值。calendar 使用的是 jQuery UI 里的 datepicker 
下图只是一个简单的demo,没有复杂的样式表:

为了灵活对应不同的表格,提取了一个共通的 js 来处理,作为使用前提:
1. table 必须有 id;
2. 有 id 的 tr 才会被复制;(tr的id从1开始编号)
3. table 内所有id都必须以 xxx_n 编号

function RowCopyUtility(opts) {
  // 表格Id
  this.tableId = opts.tableId;
  // 分组内有多少行
  this.rowGroupNumber = opts.rowGroupNumber;
  // 一组内Button对应的方法Map(key=Button value, value=对应方法名)
  // 所有方法都应以 function (idx) 方式调用
  this.buttonHandlers = opts.buttonHandlers;
  
  this._countForRowsGroup = -1;
  this._keyForRow = -1;

  this.getTargetRowGroup = function(groupIdx) {

    var rows = [];
    if (groupIdx > 0) {
      for(var i=1; i<this.rowGroupNumber+1; i++) {
        rows[i-1] = $("#row" + i + "_" + groupIdx);
      }
    } else {
      for(var i=0; i<this.rowGroupNumber; i++) {
        rows[i] = $("#" + this.tableId + " tr[id]").eq(i);
      }
    }
    return rows;
  };

  this.addRow = function (groupIdx, needCopyValue) {

    if (this._countForRowsGroup == -1) {
      this._countForRowsGroup = ($("#" + this.tableId + " tr[id]").length - 1)/this.rowGroupNumber;
      this._keyForRow =  parseInt($("#" + this.tableId + " tr[id]:not(#row_add):last").attr("id").split("_")[1]) + 1;
    }

    if (groupIdx == 0) {
      var firstRow = $("#" + this.tableId + " tr[id]:first");
      var currentIdx = firstRow.attr("id").split("_")[1];
      groupIdx = currentIdx;
    }

    var regForId = new RegExp("^(\\w+_)" + groupIdx + "$");
    var regForName = new RegExp("^(\\w+_)" + groupIdx + "$");
    var regForRadioId = new RegExp("^(\\w+_)" + groupIdx + "(.*)$");

    var targetRows = this.getTargetRowGroup(groupIdx);

    // 重要:注意闭包参数的作用域
    var idx = this._keyForRow;

    for(var i=0; i<targetRows.length; i++) {
      // clone target rows
      var cloneRow = targetRows[i].clone(false);
      var newRowId = cloneRow.attr("id").split("_")[0] + "_" + idx;
      cloneRow.attr("id", newRowId);

      var radios = [];
      cloneRow.find("[id]").each(function() {
          var id = $(this).attr("id");
          var oldId = id;
          var name = $(this).attr("name");
         
          id = id.replace(regForId, "$1" + idx);
          $(this).attr("id", id);
         
          var newname = name.replace(regForName, "$1" + idx);
          $(this).attr("name", newname);
          
          if ($(this).hasClass("hasDatepicker")) {
          	  $(this).removeClass("hasDatepicker");
          }
         
          if ($(this).attr("type") == "checkbox") {
              if($(this).next().attr("for") != "") {
                  $(this).next().attr("for", id);
              }
              if (!needCopyValue) {
            	  $(this).attr("checked", "");
              }
          }
          else if ($(this).attr("type") == "radio") {           
              id = id.replace(regForRadioId, "$1" + idx);
              $(this).attr("id", id);
         
              var radio = new Object();
              radio.id = id;
              radio.oldId = oldId;
              radio.name = name;
              radio.newname = newname;
              // IE7&#39;s Bug
              radio.checked = document.getElementById(oldId).checked;
              radios[radios.length] = radio;
         
              if($(this).next().attr("for") != "") {
                  $(this).next().attr("for", id);
              }
            
              if (!needCopyValue) {
            	  $(this).attr("checked", "");
              }
          }
          else if ($(this).attr("tagName") == "SELECT") {
	          if (needCopyValue) {
	          	  $(this).val(document.getElementById(oldId).value);
	          }
          }
          else if ($(this).attr("tagName") == "TEXTAREA" || 
                   $(this).attr("type") == "text" || 
                   $(this).attr("type") == "hidden") {
	          if (!needCopyValue) {
	              $(this).val("");
	          }
          }
      });

      // insert into document
      cloneRow.insertBefore("#" + this.tableId + " tr:last");

      // replace name for radio
      for(var n=0; n<radios.length; n++) {
         document.getElementById(radios[n].id).outerHTML =
           document.getElementById(radios[n].id).outerHTML.replace(radios[n].name, radios[n].newname);
         // IE7&#39;s Bug
         document.getElementById(radios[n].oldId).checked = radios[n].checked;
      }

      // Event Handler
      var maps = this.buttonHandlers;
      cloneRow.find("input:button").each(function() {
         var value = $(this).attr("value");
        
         var funcName = maps[value];
         if (funcName != undefined) {         
	         var func = null;
	         func = function() { eval(funcName + "(" + idx + ")"); };
	         	
	         if (func != null) {
	           $(this).attr("onclick", "");
	           $(this).unbind("click");
	           $(this).attr("onclick", "").click(func);
	         }
         }
      });
    }

    this._countForRowsGroup++;
    this._keyForRow++;
   
  };


  this.copyRow = function(groupIdx) {
    this.addRow(groupIdx, true);
  };

  this.deleteRow = function(groupIdx) {

    if (this._countForRowsGroup == -1) {
      this._countForRowsGroup = ($("#" + this.tableId + " tr[id]").length - 1)/this.rowGroupNumber;
      this._keyForRow =  parseInt($("#" + this.tableId + " tr[id]:not(#row_add):last").attr("id").split("_")[1]) + 1;
    }

    var allRows = $("#" + this.tableId + " tr[id]");
    var miniRowsCount = this.rowGroupNumber + 1;
    var tbl = $("#" + this.tableId);

    if (allRows.length == miniRowsCount) {
      tbl.find("input:text").each(function() { $(this).val(""); });
      tbl.find("textarea").each(function() { $(this).val(""); });
      tbl.find("input:hidden").each(function() { $(this).val(""); });
      tbl.find("input:radio").each(function() { $(this).attr("checked", ""); });
      tbl.find("input:checkbox").each(function() { $(this).attr("checked", ""); });
      tbl.find("select").each(function() { document.getElementById($(this).attr("id")).selectedIndex = 0; });
      tbl.find(".fg-common-field-errored").each(function() {
        $(this).removeClass("fg-common-field-errored");
      });
      return;
    }

    for(var i=1; i<this.rowGroupNumber+1; i++) {
      tbl.find("#row" + i + "_" + groupIdx).remove();
    }

    this._countForRowsGroup--;
  };

}
登入後複製

实际遇到的问题与解决办法:
1. jQuery 的 Clone() 方法,就算传入 false,元素的事件依然会被复制过来。(IE测试)
2. attr("name", name); 在IE中,不会直接替换掉,而是生成 submitName 保存。在 IE7 里 radio 会因为 name 相同而出现问题。
3. 在大量的匿名方法中,特别要注意闭包封送参数的作用域。
4. IE7里的Bug:在radio被复制时,原来的元素的选择值就没了。因此在复制前保存了复制源的radio属性,加入document之后再次设定:

// replace name for radio
for(var n=0; n<radios.length; n++) {
   document.getElementById(radios[n].id).outerHTML =
     document.getElementById(radios[n].id).outerHTML.replace(radios[n].name, radios[n].newname);
   // IE7&#39;s Bug
   document.getElementById(radios[n].oldId).checked = radios[n].checked;
}
登入後複製

5. jQuery里清除事件单独用 attr("onclick", "") 并不好用;后期用 click(function) 绑定的事件用 unbind("click") 可以移除。

if (func != null) {
  $(this).attr("onclick", "");
  $(this).unbind("click");
  $(this).attr("onclick", "").click(func);
}
登入後複製

6. jQuery UI 的 DatePicker 当创建了 datepicker 之后,可以通过 hasClass("hasDatepick") 判断是否存在,否则在复制之后有问题。
(多次复制之后 datepicker settings 会莫名其妙丢失)

7. 其他,剩下就是要注意 jQuery 选择器不要过度使用了,越复杂的表达式效率越低。
顺便推荐看一下:15个值得开发人员关注的jQuery开发技巧和心得

还要说下IE9 的 debug 工具真心不错,提高不少开发效率哦一定要利用。

就这些,希望能对大家有帮助。最后附上,测试用的 html:

<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<style>
body{font-family:&#39;Open Sans&#39;,arial,sans-serif;}
tr{height:30px}
input.button{width:60px}
table.main {
	border-width: 2px;
	border-spacing: 1px;
	border-style: solid;
	border-color: gray;
	border-collapse: collapse;
	background-color: white;
}
table.main th {
	border-width: 1px;
	padding: 5px;
	border-style: inset;
	border-color: gray;
	background-color: #f0f0f0;
	-moz-border-radius: ;
}
table.main td {
	border-width: 1px;
	padding: 5px;
	border-style: inset;
	border-color: gray;
	background-color: white;
	-moz-border-radius: ;
}
</style>

<script type="text/javascript" language="JavaScript" src="jquery.js"></script>
<script type="text/javascript" language="JavaScript" src="jquery-ui.js"></script>
<script type="text/javascript" language="JavaScript" src="rowCopyUtil.js"></script>
<link rel="stylesheet" href="jquery-ui.css" type="text/css" media="all" />
<link type="text/css" href="jqueryCalendarStyle.css" rel="stylesheet" />

<script type="text/javascript" >
 var rowUtil = new RowCopyUtility(
    {
      tableId: "tab1",
      rowGroupNumber: 3,
      buttonHandlers: {"Copy":"copyRows", "Delete":"deleteRows", "calendar":"showDatepicker", "some button":"someButtonClick"}
    }
 );
   
 function showDatepicker(idx) {
      var textId = "#calendar_" + idx;
      if (!$(textId).hasClass("hasDatepicker")) {
		  var text = $(textId).datepicker({
		    showOn : "calendar",
		    dateFormat : "yy/mm/dd"
		  });
	  }
	  $(textId).datepicker(&#39;show&#39;);
 }
 
 function addRows() {
    rowUtil.addRow(0, false);
 }
 function copyRows(idx) {
    rowUtil.copyRow(idx);
 }
 function deleteRows(idx) {
    rowUtil.deleteRow(idx);
 }
 function someButtonClick(idx) {
    alert(idx);
 }
</script>
</head>
<body>
  <table id="tab1" class="main">
    <tr>
       <th>Header1</th>
       <th>Header2</th>
       <th>Header3</th>
       <th>Header4</th>
    </tr>
    <tr id="row1_0">
       <td rowspan="3" >
           <input class="button" type="button" value="Copy" onclick="copyRows(0);" />
           <input class="button" type="button" value="Delete" onclick="deleteRows(0);" />
       </td>
       <td>text:<input type="text" id="text_0" /></td>
       <td>
           <input type="radio" name="radioAB_0" id="radioA_0" value="1" /><label for="radioA_0">Raido_A </label>
           <input type="radio" name="radioAB_0" id="radioB_0" value="2" /><label for="radioB_0">Radio_B </label>
       </td>
       <td>
           <select id="select_0">
              <option value="0">---select---</option>
              <option value="1">select option1</option>
              <option value="2">select option2</option>
           </select>
       </td>
    </tr>
    <tr id="row2_0">
      <td>
          <input type="checkbox" id="checkA_0" /><label for="checkA_0">Check_A </label>
          <input type="checkbox" id="checkB_0" /><label for="checkB_0">Check_B </label>
      </td>
      <td colspan="2">
        <input type="text" id="calendar_0" style="width:90px"/><input type="button" value="calendar" onclick="showDatepicker(0);" />
        <input type="button" value="some button" onclick="someButtonClick(0);" />
      </td>
    </tr>
    <tr id="row3_0">
      <td colspan="3">
        textarea:<textarea id="textarea_0" style="width:100%"></textarea>
      </td>
    </tr>
    <tr id="row_add">
      <td colspan="4">
      	<input class="button" type="button" value="Add" onclick="addRows();" />
      </td>
    </tr>
  </table>
</body>

</html>
登入後複製

以上是利用 jQuery Clone進行複製操作的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

qq音樂歌詞怎麼複製 歌詞複製的方法 qq音樂歌詞怎麼複製 歌詞複製的方法 Mar 12, 2024 pm 08:22 PM

  我們用戶們在使用這款平台的時候應該都能夠了解到上面對於一些功能的多樣性,我們知道一些歌曲的歌詞都寫的非常的不錯。有時候甚至都會多聽幾遍,覺得其中的含義都是非常深刻的,所以我們想要去了解其中的勝意,就想要直接的複製下來當文案來使用,不過對於要使用的話,還是要學會如何去複製歌詞才可以,這些操作方面我相信大家們應該都並不模式,但是在手機上面操作確實是有點難度,所以為了能夠讓大家們更好的了解的話,今日小編就來為你們好好的講解上面的一些操作體驗,如果你們也喜歡的話,就和小編一起來看看吧,不要錯過了。 

jQuery中如何使用PUT請求方式? jQuery中如何使用PUT請求方式? Feb 28, 2024 pm 03:12 PM

jQuery中如何使用PUT請求方式?在jQuery中,發送PUT請求的方法與發送其他類型的請求類似,但需要注意一些細節和參數設定。 PUT請求通常用於更新資源,例如更新資料庫中的資料或更新伺服器上的檔案。以下是在jQuery中使用PUT請求方式的具體程式碼範例。首先,確保引入了jQuery庫文件,然後可以透過以下方式發送PUT請求:$.ajax({u

jQuery小技巧:快速修改頁面所有a標籤的文本 jQuery小技巧:快速修改頁面所有a標籤的文本 Feb 28, 2024 pm 09:06 PM

標題:jQuery小技巧:快速修改頁面所有a標籤的文字在網頁開發中,我們經常需要對頁面中的元素進行修改和操作。使用jQuery時,有時候需要一次修改頁面中所有a標籤的文字內容,這樣可以節省時間和精力。以下將介紹如何使用jQuery快速修改頁面所有a標籤的文本,同時給出具體的程式碼範例。首先,我們需要引入jQuery庫文件,確保在頁面中引入了以下程式碼:&lt

jQuery如何移除元素的height屬性? jQuery如何移除元素的height屬性? Feb 28, 2024 am 08:39 AM

jQuery如何移除元素的height屬性?在前端開發中,經常會遇到需要操作元素的高度屬性的需求。有時候,我們可能需要動態改變元素的高度,而有時候又需要移除元素的高度屬性。本文將介紹如何使用jQuery來移除元素的高度屬性,並提供具體的程式碼範例。在使用jQuery操作高度屬性之前,我們首先需要了解CSS中的height屬性。 height屬性用於設定元素的高度

使用jQuery修改所有a標籤的文字內容 使用jQuery修改所有a標籤的文字內容 Feb 28, 2024 pm 05:42 PM

標題:使用jQuery修改所有a標籤的文字內容jQuery是一款受歡迎的JavaScript庫,被廣泛用於處理DOM操作。在網頁開發中,經常會遇到需要修改頁面上連結標籤(a標籤)的文字內容的需求。本文將介紹如何使用jQuery來實現這個目標,並提供具體的程式碼範例。首先,我們需要在頁面中引入jQuery庫。在HTML檔案中加入以下程式碼:

複製快捷鍵ctrl加什麼 複製快捷鍵ctrl加什麼 Mar 15, 2024 am 09:57 AM

在 Windows 系統中,複製的快速鍵是 Ctrl+C;在蘋果系統中,複製的快速鍵是 Command+C;在 Linux 系統中,複製的快速鍵是 Ctrl+Shift+C。了解這些快捷鍵可以提高使用者的工作效率,方便地進行文字或檔案複製操作。

excel複製表格保留原格式怎麼操作? excel複製表格保留原格式怎麼操作? Mar 21, 2024 am 10:26 AM

我們常常會用Excel處理多個表格數據,而設定好的表格經過複製貼上後,原有的格式又恢復預設了,還得需要我們重新設定。其實有方法可以讓Excel複製表格保留原格式的,下面小編就跟大家講解下具體的方法。一、Ctrl鍵拖曳複製操作步驟:使用快速鍵【Ctrl+A】全選表格內容後,將滑鼠遊標移至表格邊緣直到出現移動遊標。按住【Ctrl】鍵,接著拖曳表格到所需位置即可完成移動。需要注意的是,這種方法只適用於單一工作表,無法在不同工作表之間進行移動。二、選擇性貼上步驟:按【Ctrl+A】快速鍵全選中表格,按

如何備份CMS織夢資料庫檔案? 如何備份CMS織夢資料庫檔案? Mar 13, 2024 pm 06:09 PM

如何備份CMS織夢資料庫檔案?在使用CMS織夢建站的過程中,保障資料庫檔案的安全性是非常重要的,以防止資料遺失或損壞。備份資料庫檔案是一項必不可少的操作,以下將介紹如何備份CMS織夢資料庫檔案並附上具體程式碼範例。一、使用phpMyAdmin進行備份phpMyAdmin是常用的資料庫管理工具,透過它可以方便地對資料庫進行備份作業。以下是使用phpMyAdm

See all articles