最近客串了一把前端,有行复制的功能用 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

JavaScript는 웹 페이지의 상호 작용과 역학을 향상시키기 때문에 현대 웹 사이트의 핵심입니다. 1) 페이지를 새로 고치지 않고 콘텐츠를 변경할 수 있습니다. 2) Domapi를 통해 웹 페이지 조작, 3) 애니메이션 및 드래그 앤 드롭과 같은 복잡한 대화식 효과를 지원합니다. 4) 성능 및 모범 사례를 최적화하여 사용자 경험을 향상시킵니다.

C 및 JavaScript는 WebAssembly를 통한 상호 운용성을 달성합니다. 1) C 코드는 WebAssembly 모듈로 컴파일되어 컴퓨팅 전력을 향상시키기 위해 JavaScript 환경에 도입됩니다. 2) 게임 개발에서 C는 물리 엔진 및 그래픽 렌더링을 처리하며 JavaScript는 게임 로직 및 사용자 인터페이스를 담당합니다.

JavaScript는 웹 사이트, 모바일 응용 프로그램, 데스크탑 응용 프로그램 및 서버 측 프로그래밍에서 널리 사용됩니다. 1) 웹 사이트 개발에서 JavaScript는 HTML 및 CSS와 함께 DOM을 운영하여 동적 효과를 달성하고 jQuery 및 React와 같은 프레임 워크를 지원합니다. 2) 반응 및 이온 성을 통해 JavaScript는 크로스 플랫폼 모바일 애플리케이션을 개발하는 데 사용됩니다. 3) 전자 프레임 워크를 사용하면 JavaScript가 데스크탑 애플리케이션을 구축 할 수 있습니다. 4) node.js는 JavaScript가 서버 측에서 실행되도록하고 동시 요청이 높은 높은 요청을 지원합니다.

Python은 데이터 과학 및 자동화에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 데이터 처리 및 모델링을 위해 Numpy 및 Pandas와 같은 라이브러리를 사용하여 데이터 과학 및 기계 학습에서 잘 수행됩니다. 2. 파이썬은 간결하고 자동화 및 스크립팅이 효율적입니다. 3. JavaScript는 프론트 엔드 개발에 없어서는 안될 것이며 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축하는 데 사용됩니다. 4. JavaScript는 Node.js를 통해 백엔드 개발에 역할을하며 전체 스택 개발을 지원합니다.

C와 C는 주로 통역사와 JIT 컴파일러를 구현하는 데 사용되는 JavaScript 엔진에서 중요한 역할을합니다. 1) C는 JavaScript 소스 코드를 구문 분석하고 추상 구문 트리를 생성하는 데 사용됩니다. 2) C는 바이트 코드 생성 및 실행을 담당합니다. 3) C는 JIT 컴파일러를 구현하고 런타임에 핫스팟 코드를 최적화하고 컴파일하며 JavaScript의 실행 효율을 크게 향상시킵니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

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