单击时更新元素文本

时间:2016-12-30 09:12:42

标签: javascript jquery ajax

$("#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'),但是在调用后,它不再起作用了吗?

我做错了什么

4 个答案:

答案 0 :(得分: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()已弃用[{3}}

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

答案 1 :(得分: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
    });
});

答案 2 :(得分: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
    });
});

答案 3 :(得分:0)

在该上下文中,这是第一次引用“span”,第二次引用窗口对象。 除此之外,委托是旧的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
    });
});