2012-05-29 40 views
0


我怎麼能有這樣的事情:添加事件一次

<input class="myClass" id="a" type="checkbox" other="x"/> 
<input class="myClass" id="b" type="checkbox" other="x"/> 
<input class="myClass" id="c" type="checkbox" other="x"/> 
<input class="myClass" id="d" type="checkbox" other="y"/> 
<input class="myClass" id="e" type="checkbox" other="z"/> 

我可以檢索元素A至E,增加一個點擊事件,我想在元素上添加事件定義中attribut other(x,y和z)。
我該怎麼做?
我嘗試:

$(".myClass").each(function() { 
    $("#" + $(this).attr("other")).click(function() { 
     ... 
    }); 
}); 

但三個要素有other="x"因此事件是x上添加三個時間,我想只有一個。

回答

1

可能有更好的辦法,但你可以取消綁定此類型的任何一個事件處理程序,使用namespaces [docs]

$(".myClass").each(function() { 
    $("#" + $(this).attr("other")).off('click.someNS').on('click.someNS', function() { 
     ... 
    }); 
}); 

另一種方式是過濾元素,使您只有一個每個具有一定的other屬性:

var seen = {}; 

$(".myClass").filter(function() { 
    var other = $(this).attr('other'); 
    return !seen[other] && (seen[other] = true); 
}).each(...); 
+0

我與「關上」的解決方案去了。謝謝 – Snote

1

試試這個,我拆散結合新的人之前的事件。 Demo on JsFiddle

$(".myClass").each(function() { 
    $("#" + $(this).attr("other")).unbind('click').click( function() { 
     alert(this.id); 
    }); 
}); 
+0

這仍然會將事件處理程序三次添加到'x'。 –

+0

Infact每次都迭代其他= x的所有元素,並且您正確指向。現在我改變了我的答案,我希望現在好了。 – Adil

+0

這將事件處理程序綁定到輸入元素,而不綁定到'other'屬性中引用的元素。 –