2012-01-20 5 views
2

특정 DOM 요소를 특정 JS 개체로 참조하려면 어떻게해야합니까? 예를 들어 고객의 배열이 있습니다. jQuery를 사용하여 각 고객에 대해 LI로 확인란을 만들고 고객 이름에 스팬을 사용합니다. 확인란을 클릭하면 고객 JS 객체에 대한 처리가 필요합니다. 질문, 어떻게이 JS 개체를 쉽게 얻을 수 있습니다. 현재 나는 다음과 같은 한 : 나는 JS의 세계를 믿고 jQuery를 그것을 할 더 우아한 방법이 존재DOM 요소에 대한 JS 개체 참조

$(customers).each(function(){ 
$("<li>").append($("<input type=\"checkbox\"").attr("id","chk_" + this.ID)).append($("<span>").text(this.Name)).appendTo("#ulCustomers"); 
}); 

$("#ulCustomers input[type=checkbox]").bind("click",function(){ 

var customerId = $(this).attr("id").replace("chk_",""); 
var CustomerObj = $(customers).filter(function() { return this.ID == customerId }).get(0); 

myProcess(CustomerObj); //Two above two lines are just for select correct customer from array. 
}); 

. 감사합니다.

답변

2

같은

:.

$ ("체크 박스") 데이터 (' 고객 ', this.ID); 그것이 가장 쉬운 방법 네)

+0

물론, 어떻게 잊어 버릴 수 있습니다. 데이터() !!! :) 고마워. –

1

클릭 이벤트를 관련 고객 개체에 대한 참조로 마감 처리 할 수 ​​있습니까? 당신은 그냥 같이, jQuery를 데이터를 사용하는 것이

$(customers).each(function() { 
    var elem = $("<li><input type='checkbox'><span>" + this.Name + "</span></li>").appendTo("#ulCustomers"); 
    elem.find("input").data("customer", this); 
}); 

$("#ulCustomers input[type=checkbox]").click(function() { 
    var CustomerObj = $(this).data("customer"); 
    myProcess(CustomerObj); 
}); 
+0

을,하지만 난 노력하고있어,

$("#ulCustomers input[type=checkbox]").bind("onchange",function(){ var customerId = $(this).data("customer"); var CustomerObj = $(customers).filter(function() { return this.ID == customerId }).get(0); myProcess(CustomerObj); //Two above two lines are just for select correct customer from array. }); 

또한, 가 onchange를 이벤트를 사용, 체크 박스에 이벤트를 클릭하여 사용하지 마십시오

데이터를 검색하려면 이러한 유형의 폐쇄를 피하기 위해 :) –

0

JQuery와 data 기능을 사용할 수 있습니다이

$(customers) 
.each(function(){ 
    var custObj = this; 
    $("<li>") 
     .append(
      $("<input type=\"checkbox\"") 
      .append($("<span>") 
      .text(this.Name)) 
      .appendTo("#ulCustomers") 
      .bind("click", function(){ 
       myProcess(custObj); 
      }) 
}); 
+0

전체 고객 obj에 대한 ref를 데이터로 저장하는 것이 이드보다 더 효율적일 것입니다. 나는 onchange가 존재한다는 것을 알고 있지만, onclick을 사용하도록하고 그 다음에 그것이 체크되었는지를 확인합니다. :) –