クラスセレクターの特定の状況で、コンテキスト $(this) が変化するようです。以下の JavaScript をデバッグするのにかなりの時間を費やしましたが、これはあまり得意ではありません。
$.fn.specialbutton = function(callback) {
$(this).bind('click', function() { // $(this) is the a.button, as expected
$.ajax({
url: 'ajax.php',
data: callback(); // context pitfall
}).done(function(response) {
$(this).html(response); // context changed to something unknown
})
});
}
$('a.button').specialbutton(function() {
// context pitfall
return {
id: $(this).data('id'); // $(this) is not what you expect
};
});
最終的に、解決策はコンテキストを保存し、コールバックの明示的な呼び出しを使用することだと思います。
$.fn.specialbutton = function(callback) {
$(this).bind('click', function() { // $(this) is the a.button, as expected
var $this = $(this); // save the context;
$.ajax({
url: 'ajax.php',
data: callback.call($this); // explicitly specify context
}).done(function(response) {
$this.html(response); // reuse the saved context
})
});
}
$('a.button').specialbutton(function() {
// context pitfall
return {
id: $(this).data('id'); // $(this) is what was specified in prototype
};
});
コンテキストの変更のルールと理由は何ですか? これは設計上の特徴ですか、それとも制限ですか? これは、セレクターが HTML id セレクター、つまり$('a#button')
. 上記をコーディングするためのより良い、または一般的な方法は何でしょうか?