jQuery Clone을 사용하여 복사
最近客串了一把前端,有行复制的功能用 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'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'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'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:'Open Sans',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('show'); } 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











우리 사용자는 이 플랫폼을 사용할 때 일부 기능의 다양성을 이해할 수 있어야 합니다. 우리는 일부 노래의 가사가 매우 잘 쓰여져 있다는 것을 알고 있습니다. 때로는 여러 번 들어도 그 의미가 매우 심오하다고 느낄 때가 있기 때문에 그 의미를 이해하고 싶으면 직접 복사해서 카피라이팅으로 사용하고 싶을 때도 있습니다. 가사 복사하는 방법만 배우면 됩니다. 이러한 작업은 모두가 익숙할 것이라고 생각하지만 실제로 휴대폰에서 작업하는 것은 다소 어렵습니다. 따라서 오늘 편집자는 더 나은 이해를 돕기 위해. 위의 운영 경험 중 일부에 대한 좋은 설명이 있습니다. 마음에 드시면 꼭 오셔서 편집자와 함께 살펴보세요.

jQuery에서 PUT 요청 방법을 사용하는 방법은 무엇입니까? jQuery에서 PUT 요청을 보내는 방법은 다른 유형의 요청을 보내는 것과 유사하지만 몇 가지 세부 사항과 매개 변수 설정에 주의해야 합니다. PUT 요청은 일반적으로 데이터베이스의 데이터 업데이트 또는 서버의 파일 업데이트와 같은 리소스를 업데이트하는 데 사용됩니다. 다음은 jQuery에서 PUT 요청 메소드를 사용하는 구체적인 코드 예제입니다. 먼저 jQuery 라이브러리 파일을 포함했는지 확인한 다음 $.ajax({u를 통해 PUT 요청을 보낼 수 있습니다.

jQuery를 사용하여 요소의 높이 속성을 제거하는 방법은 무엇입니까? 프런트엔드 개발에서는 요소의 높이 속성을 조작해야 하는 경우가 종종 있습니다. 때로는 요소의 높이를 동적으로 변경해야 할 수도 있고 요소의 높이 속성을 제거해야 하는 경우도 있습니다. 이 기사에서는 jQuery를 사용하여 요소의 높이 속성을 제거하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. jQuery를 사용하여 높이 속성을 연산하기 전에 먼저 CSS의 높이 속성을 이해해야 합니다. height 속성은 요소의 높이를 설정하는 데 사용됩니다.

제목: jQuery 팁: 페이지에 있는 모든 태그의 텍스트를 빠르게 수정하세요. 웹 개발에서는 페이지의 요소를 수정하고 조작해야 하는 경우가 많습니다. jQuery를 사용할 때 페이지에 있는 모든 태그의 텍스트 내용을 한 번에 수정해야 하는 경우가 있는데, 이는 시간과 에너지를 절약할 수 있습니다. 다음은 jQuery를 사용하여 페이지의 모든 태그 텍스트를 빠르게 수정하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 먼저 jQuery 라이브러리 파일을 도입하고 다음 코드가 페이지에 도입되었는지 확인해야 합니다. <

Windows 시스템에서 복사할 단축키는 Ctrl+C이고, Linux 시스템에서는 복사할 단축키는 Ctrl+Shift+C입니다. 이러한 바로 가기 키를 알면 사용자의 작업 효율성이 향상되고 텍스트 또는 파일 복사 작업이 쉬워집니다.

우리는 여러 테이블 데이터를 처리하기 위해 엑셀을 자주 사용하는데, 설정된 테이블을 복사하여 붙여넣은 후 원래 형식이 기본값으로 돌아가므로 이를 재설정해야 합니다. 실제로 엑셀 복사표를 원본 형식으로 유지하는 방법이 있습니다. 구체적인 방법은 아래에서 편집자가 설명해 드리겠습니다. 1. Ctrl 키 드래그 및 복사 작업 단계: 단축키 [Ctrl+A]를 사용하여 모든 테이블 내용을 선택한 다음 움직이는 커서가 나타날 때까지 마우스 커서를 테이블 가장자리로 이동합니다. [Ctrl] 키를 누른 채 테이블을 원하는 위치로 드래그하면 이동이 완료됩니다. 이 방법은 단일 워크시트에서만 작동하며 다른 워크시트 간에 이동할 수 없다는 점에 유의해야 합니다. 2. 선택 붙여넣기 방법: [Ctrl+A] 단축키를 눌러 모든 테이블을 선택하고,

제목: jQuery를 사용하여 모든 태그의 텍스트 내용을 수정합니다. jQuery는 DOM 작업을 처리하는 데 널리 사용되는 인기 있는 JavaScript 라이브러리입니다. 웹 개발을 하다 보면 페이지에 있는 링크 태그(태그)의 텍스트 내용을 수정해야 하는 경우가 종종 있습니다. 이 기사에서는 jQuery를 사용하여 이 목표를 달성하는 방법을 설명하고 구체적인 코드 예제를 제공합니다. 먼저 페이지에 jQuery 라이브러리를 도입해야 합니다. HTML 파일에 다음 코드를 추가합니다.

CMS DreamWeaver 데이터베이스 파일을 백업하는 방법은 무엇입니까? CMS를 사용하여 웹 사이트를 구축하는 과정에서 데이터 손실이나 손상을 방지하기 위해 데이터베이스 파일의 보안을 보장하는 것은 매우 중요합니다. 데이터베이스 파일을 백업하는 것은 필수적인 작업입니다. 다음에서는 CMS DreamWeaver 데이터베이스 파일을 백업하는 방법과 구체적인 코드 예제를 첨부하는 방법을 소개합니다. 1. 백업을 위해 phpMyAdmin을 사용하십시오. phpMyAdmin은 데이터베이스를 쉽게 백업할 수 있는 일반적으로 사용되는 데이터베이스 관리 도구입니다. 다음은 phpMyAdm을 사용하고 있습니다.
