이 코드를 만들었지 만 완료하는 방법을 모르겠습니다. 나는 개체가 ContactDetail
있습니다. 또한 하나의 프로토 타입 메서드가 doSomething
있습니다. 각 ContactDetail
인스턴스에는 optionEl
html 옵션 요소 인 속성 이 있습니다. 몇 가지 인스턴스를 만들고 선택할 옵션을 추가했습니다. 이제 선택에서 값을 선택하면 선택에 doSomething
따라 메소드 를 호출하고 싶습니다 . 나는 HTML 변경 (ID 선언 없음)없이 일부 솔루션을하고 싶습니다. 또한 순수한 자바 스크립트 (jquery 데이터 없음)로 솔루션을 고맙게 생각합니다. 나는 이것을 스스로 코딩 할 것이지만 지금은 아이디어가 없습니다. 그래서 나는 당신에게 도움을 요청합니다.
EDIT1 : 때로는 옵션이 분리되거나 추가되어 다시 선택하기 때문에 색인이 작동하지 않습니다.
EDIT2 : 내 예제를 수정해야 했으므로 더 잘 이해할 수 있습니다.
다음은 jsfiddle입니다 : http://jsfiddle.net/kkha3/
var selectDetail = $("<select />");
var ContactDetail = function(name) {
this.name = name;
this.optionEl = $("<option/>").text(this.name);
// there are like 5 more properties
}
ContactDetail.prototype.doSomething = function() {
console.log(this.name); // this is just a debug, that proves in example
// that correct instance was called, but there is no
// such a thing in fact
// here I call some more things based choice
// for example if you select contact detail address,
// then it puts into form more inputs (like ZIP, state, street..
}
var contactDetailList = [];
contactDetailList.push(new ContactDetail("a"));
contactDetailList.push(new ContactDetail("b"));
contactDetailList.push(new ContactDetail("c"));
contactDetailList.push(new ContactDetail("d"));
contactDetailList.push(new ContactDetail("e"));
contactDetailList.push(new ContactDetail("f"));
for (var i = 0; i < contactDetailList.length; i++) {
contactDetailList[i].optionEl.appendTo(selectDetail);
}
selectDetail.change(function(event) {
// how to call doSomething() on instance that is selected??
});
selectDetail.appendTo("body");
아마도 jQuery의 data () 기능으로 무언가를 할 수있을 것입니다. ContactDetail
옵션 요소에 연결되도록 "클래스"를 약간 수정합니다 .
var ContactDetail = function(name) {
this.name = name;
this.optionEl = $("<option/>").text(this.name);
// attach this ContactDetail to the option
this.optionEl.data('contact-detail', this);
}
그런 다음 나중에 변경 처리기에서 선택한 옵션 요소를 가져오고 여기에서 ContactDetail
클래스 의 인스턴스를 검색 할 수 있습니다 .
select.change(function(event) {
var contactDetail = $('option:selected', this).data('contact-detail');
if (contactDetail)
contactDetail.doSomething();
});
이렇게하면 목록을 작성하는 데 사용한 전역 배열에서 완전히 자유 로워집니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다