我有一個相對於此代碼的問題。它應該(並且它)顯示項目列表,您可以通過點擊加號和減號來添加和刪除條目。Javascript代碼行爲意外
<html><head><script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.3.2");
app={};
app.attachList = function() {
return {
_current_id : 0,
addFilterAfter : function(after_entry_id) {
that = this;
new_id = this._newId();
jQuery("#entry_"+after_entry_id).after("<li id=\"entry_"
+new_id+"\"><a href=\"javascript:void(0);\" id=\"entry_"
+new_id+"_add\">(+)</a><a href=\"javascript:void(0);\">(-)</a> hello "
+new_id+"</li>");
jQuery("#entry_"+new_id+"_add")
.bind("click", function() {
that.addFilterAfter(new_id);
}
);
},
show : function() {
that = this;
new_id = this._newId();
jQuery("#list").children().remove();
jQuery("#list").append("<li id=\"entry_"
+new_id+"\"><a href=\"javascript:void(0);\" id=\"entry_"
+new_id+"_add\">(+)</a> hello </li>");
jQuery("#entry_"+new_id+"_add")
.bind("click", function() {
alert(new_id); // HERE
that.addFilterAfter(new_id);
}
);
},
_newId : function() {
this._current_id++;
return this._current_id;
},
};
}
app.main = function() { l = app.attachList(); l.show(); }
google.setOnLoadCallback(function() { jQuery.noConflict(); jQuery(document).ready(app.main); });
</script>
<ul id="list" /></ul>
</head>
</html>
我的問題是相對於在標有HERE的行發生的情況。理想情況下,如果我點擊第一個項目+,我希望這個代碼繼續添加到第一個項目的下方。這不會發生。它會繼續遞增new_id(正如您從警報中看到的那樣),而不是保留授予的原始new_id。
現在,我懷疑發生了什麼事情,主要涉及javascript的閉包性質,但我想聽到它從更熟練的人那裏解釋。作爲一個側面說明,如果我用一個單獨的方法劃分綁定事件的邏輯,它按預期工作...從這個我的犯罪嫌疑人。
ARGHHHHHHHHH! :D – 2009-12-28 05:41:27
謝謝。我認爲new_id被保存爲函數內this._current_id的引用。相反,我只是指一個該死的全球:)。但後來我不明白爲什麼,當我在不同的方法例程中隔離bind()調用時,它正常工作。 – 2009-12-28 05:45:08
但是,經驗教訓。我不會在我的javascript生活中忘記'var'。 – 2009-12-28 05:46:11