clone() .insertBefore, insertAfter 交换html
- var arr = new Array();
- arr.push('<div>');
- arr.push('html test');
- arr.push('</div>');
- alert(arr.join(''));
优点不需要与后台交互,缺点用js处理临时数据时,不能刷心页面,否则数据会丢失
页面
- <input type="button" name="a" value="添加" onclick="addCardDetail()" class="button">
- <div id="details_1" class="explain-col">
- <label for="prefix_1">前缀:</label>
- <input type="text" name="detail[1][prefix]" id='prefix_1' size="5" class="input-text">
- <label for="begin_1">开始编号:</label>
- <input type="text" name="detail[1][start_sn]" id='begin_1' size="5" class="input-text">
- <label for="end_1">结束编号:</label>
- <input type="text" name="detail[1][end_sn]" id='end_1' size="5" class="input-text">
- <input type="button" value="删除" onclick="deletePurchaseDetail(1)" class="button">
- </div>
js
- <script>
- function addCardDetail() {
- lastIdAttr = $("div[id^='details_']").last().attr('id'); //最后一行的id的值
- strIndex = lastIdAttr.lastIndexOf('_') + 1; //取得id中数字的位置号
- index = parseInt(lastIdAttr.substring(strIndex)) + 1;//待增加的序号
- total = $("div[id^='details_']").size();
- if (total < 10) {
- var html = [
- '<div id="details_' + index + '" class="explain-col">',
- '<label for="prefix_' + index + '">前缀:</label>',
- '<input type="text" name="detail[' + index + '][prefix]" id="prefix_' + index + '" size="5" class="input-text">',
- '<label for="begin_' + index + '">开始编号:</label>',
- '<input type="text" name="detail[' + index + '][start_sn]" id="begin_' + index + '" size="5" class="input-text">',
- '<label for="end_' + index + '">结束编号:</label>',
- '<input type="text" name="detail[' + index + '][end_sn]" id="end_' + index + '" size="5" class="input-text">',
- '<input type="button" value="删除" onclick="deletePurchaseDetail(' + index + ')" class="button">',
- '</div>'
- ].join('');
- $(html).insertAfter("#" + lastIdAttr);
- }
- }
- function deletePurchaseDetail(i) {
- len = $("div[id^='details_']").size();
- if (len > 1 && window.confirm("确认删除本行")) {
- $("#details_" + i).remove();
- } else {
- alert('明细信息必须保留一行');
- }
- }
- </script>