2016-12-30 10 views
-1
$("#readMain").delegate("span", "click", function() { 
    var toSend = $(this).text(); 
    $(this).text(function() {return "test1";}); 
    $.post('/render/', {'word': toSend}, function(data){ 
     $(this).text(data); 
     alert(data); //for testing 
    }); 
}); 

私はクリックされた単語を更新しようとしています。それは初めてうまく動作します(それは 'test1'に変わります)。しかし、ポストコールの後、もう動作しませんか?クリックすると要素のテキストが更新されます

何が間違っている

+1

、 '.delegate'は廃止され、.on' –

答えて

0

この文脈では、これはウィンドウオブジェクトを参照する2回目の「スパン」を最初に参照します。 それ以外にも、デリゲートは古いjQueryです。今すぐ '.on'を使用できます。

あなたはこのように機能を更新するために、旧姓ます:FYI

$("#readMain").on("click", "span", function() { 
    var span = $(this); 
    var toSend = span.text(); 
    $.post('/render/', {'word': toSend}, function(data){ 
     span.text(data); 
     alert(data); //for testing 
    }); 
}); 
+0

はそんなにありがとう'使用!それは今のところ働いています – arcanelogic

+0

@arcanelogicありがとう。それがあなたを助けた場合、正しいとして私のawnserを受け入れるといいです:) – HerrWalter

1

thisをやっていることは、$.post()コールバックメソッドにspan要素を参照する変数に$(this)の参照を格納し、必要な場所にそれを使用しません。

//Store the reference 
var _this = $(this); 
$.post('/render/', {'word': toSend}, function(data){ 
    //Use it later 
    _this.text(data); 
    alert(data); //for testing 
}); 

また、delegate()が使用推奨されていません.on()

$("#readMain").on("click", "span", function() { 
    //Store the reference 
    var _this = $(this); 

    var toSend = _this.text(); 
    _this.text("test1"); 
    $.post('/render/', {'word': toSend}, function(data){ 
     _this.text(data); 
     alert(data); //for testing 
    }); 
}); 
0

thisは、...、すべての関数、クラス、閉鎖を意味し、現在のスコープ内でのみ有効で、それはthis上のしています。最初のthisへの参照をvarに保存して、後でアクセスしてください。

$("#readMain").delegate("span", "click", function() { 
    var span = $(this); 
    var toSend = span.text(); 
    span.text(function() {return "test1";}); 

$.post('/render/', {'word': toSend}, function(data){ 
     span.text(data); 
     alert(data); //for testing 
    }); 
}); 
0

$ .postコールバックのコンテキストが変更されます。変数を宣言してコンテキストを設定することができます。以下のコードを参照してください。

$("#readMain").on("span", "click", function() { 
    var self = $(this), 
     toSend = self.text(); 
    self.text(function() {return "test1";}); 
    $.post('/render/', {'word': toSend}, function(data){ 
     self.text(data); 
     alert(data); //for testing 
    }); 
}); 
関連する問題