2016-12-30 46 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

這在該上下文中是指第一次的「跨度」,它指的是窗口對象的第二次。 除此之外,委託是舊的jQuery,現在可以使用'.on'。

你的東東來更新這樣的功能:

$("#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不指span元素$.post()回調方法,存儲$(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。將一個引用保存在var中的第一個this以便稍後訪問。

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