이 코드와 관련된 질문이 있습니다. 그것은 (그리고 그것은) 플러스와 마이너스를 클릭하여 항목을 추가하고 제거 할 수있는 항목 목록을 표시해야합니다.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>
내 질문은 여기에 표시된 행에서 발생하는 것과 관련이 있습니다. 이상적으로, 첫 번째 항목 +를 클릭하면이 코드가 첫 번째 항목 바로 아래에 계속 추가 될 것으로 예상됩니다. 이것은 일어나지 않습니다. New_id를 원래대로 유지하는 대신 경고에서 알 수 있듯이 new_id가 계속 증가합니다.
이제 자바 스크립트의 폐쇄 특성을 포함하는 상황에 대해 용의자가 있습니다.하지만 더 숙련 된 사람의 설명을 듣고 싶습니다.
부수적으로, 이벤트를 별도의 방법으로 바인딩하는 논리를 분할하면 예상대로 ... 내 용의자가 작동합니다.
ARGHHHHHHHHH! : D –
감사합니다. new_id가이 함수에 대한 this._current_id에 대한 참조로 유지되었다고 생각했습니다. 대신 나는 지긋 지긋한 세계를 언급하고 있었다. :). 하지만 다른 방법 루틴에서 bind() 호출을 분리했을 때 왜 제대로 작동하는지 이해할 수 없습니다. –
하지만 교훈을 얻었습니다. 내 javascript 생활에서'var'을 더 이상 잊지 않을 것입니다. –