舊時代的OO程序員,新的JavaScript/html編碼。Javascript類生成HTML按鈕:如何實現`this`上的閉包?
所以我正在玩JavaScript的「類」,試圖製作一個可重複使用的單元,將自己寫入html。
<html>
<script>
function Foo(min_input, max_input) {
var n_min_input = min_input;
var n_input = max_input;
var curr_shown = min_input;
this.show_one_more = function() {
if (curr_shown < n_input) {
document.getElementById('input' + curr_shown).style = 'display: block';
curr_shown++;
}
}
this.show_one_less = function() {
if (curr_shown > n_min_input) {
curr_shown--;
document.getElementById('input' + curr_shown).style = 'display: none';
}
}
this.write_inputs = function() {
for (var i = 0; i < n_min_input; i++) {
document.write("<input type='text' style='display: block' value='" + i + "' id='input" + i + "' name='input" + i + "'/>");
}
for (var i = n_min_input; i < n_input; i++) {
document.write("<input type='text' style='display: none' value='" + i + "' id='input" + i + "' name='input" + i + "'/>");
}
//want to essentially do this, but don't know how
document.write("<p><input type='button' onclick='this.show_one_more()' value='+'></input><input type='button' value='-' onclick='this.show_one_less()'/></p>");
}
}
var f = new Foo(1, 5);
f.write_inputs();
//works here, but would rather it be generated in f.write_inputs();
document.write("<p><input type='button' onclick='this.show_one_more()' value='+'></input><input type='button' value='-' onclick='this.show_one_less()'/></p>");
</script>
<input type="button" value="stuff" id="sbutton"/>
</html>
所以基本上,我想在按鈕上的文檔編寫調用中得到某種封閉。我覺得這是人們以前可能用過的模式(但我可能完全錯誤)。我的想法:
使全局變量var foo_idx=0
和數組var allfoos = [];
。在初始化(類的主體)做this.foo_idx=foo_idx; allfoos[foo_idx]=this;foo_idx++
,然後我可以使用allfoos[foo_idx]
來捕獲這個。但感覺哈克。人們通常如何創建可重用的html元素?
首先,也是最重要的一點:__DROP__'document.write'。它只能用於在頁面加載時將內容寫入當前文檔 - 之後對其進行的任何調用(如從函數內部)_overwrites_當前文檔。閱讀如何使用DOM方法創建元素,或者使用'.innerHTML',或者 - 不要重新發明輪子,而是使用一個庫,而不是已經有更復雜的DOM操作方法的庫。 – CBroe