問題
有沒有遇到過這樣的需求, 在頁面上會有不定個input, 點擊添加按鈕就添加

每次寫這玩意好麻煩啊, 把他封裝起來, 需要的時候調用就好了
思路
因為每個input標簽的name如果相同的話, 在后端接收的時候會出錯, 所以我的解決辦法就是在name后加上一個數字, 后端用一個循環進行接收
點擊第一行的添加
點擊的時候, 將div准備好, 添加到內容div中的第一個
點擊每行的添加
將div添加到當前點擊行后面一個
點擊每行刪除
刪除當前div
實現
基本思路很簡單, 只要在每個點擊按鈕上添加對應的點擊事件, 將結果封裝成類.
我在封裝的時候喜歡先想用的時候怎么用, 然后根據這個思路來想應該怎么封裝, 思考如下
- 因為添加的div肯定是不同的, 是需要傳的參數, 但是如果直接傳div字符串也太丑了, 應該在頁面直接寫HTML, 然后傳id即可
- 添加成功后需要有個回調函數, 我得做些收尾的工作
- 最好有這兩個參數就可以直接運行
開始碼代碼了:
在創建的時候接收參數, 大部分參數都有默認值, 也就是說, 按照默認值來看, 一個參數都不需要
當前實現還很簡陋, 代碼放在碼雲上, 發現問題再更新, 下載后可以直接運行demo文件
https://gitee.com/hujingnb/addDivItem
下面是當前的簡單實現, 要看最新代碼請移步碼雲, 歡迎提出問題
/**
* 用於添加條目, 不定數輸入框
* @param params
* @constructor
*/
function AddItem(params) {
// 接收參數
var contentDivId = params['content_div_id'] || 'content_div_id';
var exampleDivId = params['example_div_id'] || 'example_div_id';
var addButtonId = params['add_button_id'] || 'add_button_id';
this.addButton = $('#' + addButtonId);
this.contentDiv = $('#' + contentDivId);
this.exampleDiv = $('#' + exampleDivId);
this.addSuccessFunction = params['add_success'];
this.secp = params['start_num'] || 0;
this.maxNum = params['max_num'] || -1;
// 保存當前已經添加的數量
this.num = 0;
}
// 向內容div的第一個添加
AddItem.prototype.addFistItem = function () {
// 判斷是否超出最大數量
if(this.maxNum != -1 && this.num >= this.maxNum) return;
var divItem = this.getDivItem();
// 添加
this.contentDiv.prepend(divItem);
// 調用回調函數
if (this.addSuccessFunction) this.addSuccessFunction(divItem, this.secp);
// 序號迭代
this.secpIter();
// 條目+1
this.num++;
};
// 向元素后面添加
AddItem.prototype.addAfterItem = function(item) {
// 判斷是否超出最大數量
if(this.maxNum != -1 && this.num >= this.maxNum) return;
var divItem = this.getDivItem();
item.after(divItem);
// 調用回調函數
if (this.addSuccessFunction) this.addSuccessFunction(divItem, this.secp);
// 序號迭代
this.secpIter();
// 條目+1
this.num++;
};
// 獲取當前序號的div
AddItem.prototype.getDivItem = function () {
var cloneDiv = this.exampleDiv.clone();
var secp = this.secp;
// 將div的所有 input 的name加上當前序號
cloneDiv.find('input').each(function () {
var name = $(this).attr('name');
$(this).attr('name', name + '_' + secp);
});
var _this = this;
// 給添加按鈕添加點擊事件
cloneDiv.find('[add]').click(function () {
_this.addAfterItem(cloneDiv);
});
// 給刪除按鈕添加點擊事件
cloneDiv.find('[remove]').click(function () {
cloneDiv.remove();
// 條目-1
_this.num--;
});
return cloneDiv;
};
// 序號向后延展
AddItem.prototype.secpIter = function () {
this.secp += 1;
};
/**
* 運行函數
* @param num
* 初始狀態先添加幾個
*/
AddItem.prototype.run = function (num) {
var _this = this;
this.addButton.click(function () {
_this.addFistItem();
});
// 刪除示例div
this.exampleDiv.remove();
// 刪除div的id
this.exampleDiv.removeAttr('id');
if(num){
for(let i = 0; i < num; i++){
this.addFistItem();
}
}
};
