我試圖編寫一些JavaScript對象來管理頁面上的動態窗體。Jquery綁定事件初始化對象只適用於單個對象
表單對象爲表單存儲數組並將它們呈現到容器中。
我想爲每個表單上的某些字段設置單擊事件,因此決定製作一個單獨的對象,並嘗試綁定對象內的事件init
方法。
對於每一個我添加的新表單,init方法都會被清除。然而,在更改事件中,只有數組中的最後一個表單對象觸發。
JS小提琴示範發行
可以發現:here
function Form(node) {
this.node = node;
this.init = function() {
$(this.node).find("input:checkbox").change(event => {
console.log('Event fired');
});
};
this.init();
}
// Object to manage addition/removal
var forms = {
init: function() {
this.formsArray = [];
this.cacheDom();
this.bindEvents();
this.render();
}
// Only selector elems from the DOM once on init
cacheDom: function() { ... },
// Set up add/remove buttons to fire events
bindEvents: function() { ... },
render: function() {
for (let form of forms)
this.$formSetContainer.append(form.node)
}
addForm: function() {
// Logic to create newRow var
this.formsArray.push(new Form(newRow));
},
removeForm: function() {
// Logic to check if a form can be removed
this.formsArray.pop();
}
},
我已經嘗試過
實際上,我能夠通過移除結合內部render
事件this.init()
裏面的Form構造函數和改變render
像這樣:
for (let form of this.formsArray) {
this.$formSetContainer.append(form.node)
form.init();
}
那麼事件將成功地火了各種形式的
但我寧願沒有運行這段代碼每次我打電話render()
被稱爲每次我添加/刪除表格的時間時間。
我有一種感覺,這是一個範圍界定問題,或者該事件以某種方式被破壞。無論是我還是誤解事件的約束。任何指針,將不勝感激
'......事件在某種程度上被破壞了.':您可以使用瀏覽器的控制檯來查看某個元素上當前處於活動狀態的事件偵聽器([firefox](https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector/How_to/Examine_event_listeners),chrome在控制檯中擁有自己的事件列表(Elements> Event Listeners))。 'init'和'render'函數定義後缺少逗號。 我不完全理解如何區分'forms'(object)和'forms'(array)。也許改變其中一個名字(例如form_list),所以我不必擔心你正在看着你不期望的那個。 –
請提供一個說明問題的小提琴。現在你不清楚了:'newRow'似乎是一個未初始化的全局變量,'$ formSetContainer'沒有intitialised,'fucntion'有拼寫錯誤,'for(let form of forms)'應該是'(讓這個形式的形式)'。通過在代碼中放置'console.log'來打印一系列變量的當前值,您將能夠幫助自己。 – trincot
已在這裏添加小提琴:https://jsfiddle.net/rp944x19/4/ –