<p id="n9q5v"><strike id="n9q5v"></strike></p>
    1. \r\n  \r\n    \r\n       Header1<\/th>\r\n       Header2<\/th>\r\n       Header3<\/th>\r\n       Header4<\/th>\r\n    <\/tr>\r\n    \r\n       \r\n           \r\n           \r\n       <\/td>\r\n       text:<\/td>\r\n       \r\n           Raido_A <\/label>\r\n           Radio_B <\/label>\r\n       <\/td>\r\n       \r\n           \r\n              ---select---<\/option>\r\n              select option1<\/option>\r\n              select option2<\/option>\r\n           <\/select>\r\n       <\/td>\r\n    <\/tr>\r\n    \r\n      \r\n          Check_A <\/label>\r\n          Check_B <\/label>\r\n      <\/td>\r\n      \r\n        \r\n        \r\n      <\/td>\r\n    <\/tr>\r\n    \r\n      \r\n        textarea:<\/textarea>\r\n      <\/td>\r\n    <\/tr>\r\n    \r\n      \r\n      \t\r\n      <\/td>\r\n    <\/tr>\r\n  <\/table>\r\n<\/body>\r\n\r\n<\/html><\/pre>"}

      国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

      Home Web Front-end JS Tutorial Copy using jQuery Clone

      Copy using jQuery Clone

      May 14, 2018 pm 02:47 PM
      clone jquery use copy conduct

      最近客串了一把前端,有行復(fù)制的功能用 jQuery 來實現(xiàn)了。感覺比以前原生js用 CreateElement 要簡單多了,但還是遇到了一些陷阱比如IE7的bug,這里記錄下來。先看看 table 的樣子:這里3行是一組,按下"Copy"連值復(fù)制,按下"Add"只增加行不復(fù)制值。calendar 使用的是 jQuery UI 里的 datepicker?
      下圖只是一個簡單的demo,沒有復(fù)雜的樣式表:

      為了靈活對應(yīng)不同的表格,提取了一個共通的 js 來處理,作為使用前提:
      1. table 必須有 id;
      2. 有 id 的 tr 才會被復(fù)制;(tr的id從1開始編號)
      3. table 內(nèi)所有id都必須以 xxx_n 編號

      function RowCopyUtility(opts) {
        // 表格Id
        this.tableId = opts.tableId;
        // 分組內(nèi)有多少行
        this.rowGroupNumber = opts.rowGroupNumber;
        // 一組內(nèi)Button對應(yīng)的方法Map(key=Button value, value=對應(yīng)方法名)
        // 所有方法都應(yīng)以 function (idx) 方式調(diào)用
        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);
      
          // 重要:注意閉包參數(shù)的作用域
          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,元素的事件依然會被復(fù)制過來。(IE測試)
      2. attr("name", name); 在IE中,不會直接替換掉,而是生成 submitName 保存。在 IE7 里 radio 會因為 name 相同而出現(xiàn)問題。
      3. 在大量的匿名方法中,特別要注意閉包封送參數(shù)的作用域。
      4. IE7里的Bug:在radio被復(fù)制時,原來的元素的選擇值就沒了。因此在復(fù)制前保存了復(fù)制源的radio屬性,加入document之后再次設(shè)定:

      // 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 當(dāng)創(chuàng)建了 datepicker 之后,可以通過 hasClass("hasDatepick") 判斷是否存在,否則在復(fù)制之后有問題。
      (多次復(fù)制之后 datepicker settings 會莫名其妙丟失)

      7. 其他,剩下就是要注意 jQuery 選擇器不要過度使用了,越復(fù)雜的表達式效率越低。
      順便推薦看一下:15個值得開發(fā)人員關(guān)注的jQuery開發(fā)技巧和心得

      還要說下IE9 的 debug 工具真心不錯,提高不少開發(fā)效率哦一定要利用。

      就這些,希望能對大家有幫助。最后附上,測試用的 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>

      The above is the detailed content of Copy using jQuery Clone. For more information, please follow other related articles on the PHP Chinese website!

      Statement of this Website
      The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

      Hot AI Tools

      Undress AI Tool

      Undress AI Tool

      Undress images for free

      Undresser.AI Undress

      Undresser.AI Undress

      AI-powered app for creating realistic nude photos

      AI Clothes Remover

      AI Clothes Remover

      Online AI tool for removing clothes from photos.

      Clothoff.io

      Clothoff.io

      AI clothes remover

      Video Face Swap

      Video Face Swap

      Swap faces in any video effortlessly with our completely free AI face swap tool!

      Hot Tools

      Notepad++7.3.1

      Notepad++7.3.1

      Easy-to-use and free code editor

      SublimeText3 Chinese version

      SublimeText3 Chinese version

      Chinese version, very easy to use

      Zend Studio 13.0.1

      Zend Studio 13.0.1

      Powerful PHP integrated development environment

      Dreamweaver CS6

      Dreamweaver CS6

      Visual web development tools

      SublimeText3 Mac version

      SublimeText3 Mac version

      God-level code editing software (SublimeText3)

      How to copy lyrics from QQ Music How to copy lyrics How to copy lyrics from QQ Music How to copy lyrics Mar 12, 2024 pm 08:22 PM

      We users should be able to understand the diversity of some functions when using this platform. We know that the lyrics of some songs are very well written. Sometimes we even listen to it several times and feel that the meaning is very profound. So if we want to understand the meaning of it, we want to copy it directly and use it as copywriting. However, if we want to use it, we still need to You just need to learn how to copy lyrics. I believe that everyone is familiar with these operations, but it is indeed a bit difficult to operate on a mobile phone. So in order to give you a better understanding, today the editor is here to help you. A good explanation of some of the above operating experiences. If you also like it, come and take a look with the editor. Don’t miss it.?

      How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

      How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

      jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

      Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

      Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

      Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ??the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

      How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

      How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

      Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

      jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

      What does TikTok recommended video mean? How to use Douyin to recommend videos? What does TikTok recommended video mean? How to use Douyin to recommend videos? Mar 27, 2024 pm 03:01 PM

      As a world-renowned short video social platform, Douyin has won the favor of a large number of users with its unique personalized recommendation algorithm. This article will delve into the value and principles of Douyin video recommendation to help readers better understand and make full use of this feature. 1. What is Douyin recommended video? Douyin recommended video uses intelligent recommendation algorithms to filter and push personalized video content to users based on their interests and behavioral habits. The Douyin platform analyzes users' viewing history, like and comment behavior, sharing records and other data to select and recommend videos that best suit users' tastes from a huge video library. This personalized recommendation system not only improves user experience, but also helps users discover more video content that matches their preferences, thereby enhancing user stickiness and retention rate. at this

      Introduction to how to add new rows to a table using jQuery Introduction to how to add new rows to a table using jQuery Feb 29, 2024 am 08:12 AM

      jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

      See all articles