2012-01-20 20 views
2

特定のDOMオブジェクトを特定のJSオブジェクトに参照するにはどうすればよいですか? たとえば、私は顧客の配列を持っています。 jQueryを使用して、各顧客に対して、チェックボックスを含むLIと顧客名のスパンを作成します。チェックボックスをクリックすると、その顧客のJSオブジェクトに対して何らかの処理を行う必要があります。質問、どのように私はこのJSオブジェクトを簡単に得ることができます。 は現在、私は次のようしている: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. 
}); 

を私はJSとjQueryの世界でそれを行うには、よりエレガントな方法が存在すると信じています。 ありがとう

答えて

2

よう

:。

$( "チェックボックス")のデータ(」顧客 '、this.ID);データ取得するに

$("#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

もちろん、私は.data()を忘れることができます! :)ありがとう –

1

関連するCustomerオブジェクトを参照してクロージャにclickイベントをバインドできませんか?あなたは、私はちょうどこのように、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

うん、それは最も簡単な方法ですが、私がしようとしていますそのような型の閉鎖を避けるために:) –

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を格納すると思うだけでなく、より効果的にIDです。私はonchangeが存在することを知っていますが、私はonclickを使用し、それがチェックされているかどうかを確認することを前提としています:) –

関連する問題