2009-07-27 43 views
0

是不確定我有,我想取決於複選框的「檢查」狀態採取一些行動的方法。該「點擊」事件工作正常,但在foreach循環的「myFunction的」打不:「這」在jQuery的自定義方法

$(document).ready(function(){ 
    $('#TreeView1 :checkbox') 
    .click(HandleCheckbox); // Works fine 

    // Go through the entire Category treeview to 
    // see if there are any checkboxes that are already 
    // checked. 
    $.fn.myFunction = HandleCheckbox; 
    $(":checked:checkbox").each(function(index) { 
    // In the HandleCheckbox 'this' is undefined. 
    $(this).myFunction(); 
    }); 

}); 

function HandleCheckbox() { 
    alert(this.name + '=' + this.checked); 
} 

在上面的代碼中,「點擊」方法火災時,‘本’的定義,如預期。當我在foreach循環中調用'muFunction'時,'HandleCheckbox'函數中未定義'this'。

我仍然在學習jQuery的繩索,因此,如果有這樣的「好」或更簡單的方法,請讓我知道。

謝謝。

回答

6

這也將工作:

$(":checked:checkbox").each(HandleCheckbox) 
+0

這是我的情況最優雅的解決方案。謝謝。 – 2009-07-27 19:01:21

0

嘗試這種情況:

$("input:checkbox:checked").each(function(index) { 
    $(this).myFunction.apply(this); 
    }); 
3

在JavaScript中,this指對象的所有者。對於事件,這是觸發事件的對象。但是,該屬性不會從所述函數/事件處理程序中爲所調用的函數繼承。雖然人們可能會認爲它應該適用於你給出的例子,但我並不完全瞭解這門語言的複雜性,但我認爲這是這裏的罪魁禍首。一起this一個引用傳遞,如果你想使用它,就像這樣:

$(this).myFunction(this); 

這讓我想起,你可以通過解決這個問題:

// this becomes the `this` "keyword" without defining a parameter to hold it 
$(this).myFunction.apply(this); 
+0

我個人更喜歡這個,因爲它不需要一次性使用變量被定義爲無用的變量。 – 2009-07-27 18:29:59

1

解決這個範圍的通用方法問題:

parent_func = this; 
$(":checked:checkbox").each(function(index) { 
    $(parent_func).myFunction(); 
});