javascript - 你能在 $.post() 中使用 $(this) 吗?

标签 javascript jquery ajax dom

我似乎无法从 $.post 部分访问 $(this) 。它在它之外工作正常。这是 JavaScript:

    $('.idea').each(function(){
        var title = $(this).html();
        $.post("votes.php", { title: title }, function(data){
            $(this).nextAll('.voteTotal').html(data);
        }, "json");
    });

HTML:

<h3 class="idea">Idea #1</h3>
<h4 class="voteTotal"></h4>
<p>This is a really cool idea.</p>
<a href="#" class="vote">Click to vote</a>

最佳答案

你应该在回调函数之前备份this:

$(".idea").each(function() {
    var $this = $(this),
        title = $this.html();

    $.post("votes.php", { title: title }, function(data) {
        $this.nextAll(".voteTotal").html(data);
    }, "json");
});

关于javascript - 你能在 $.post() 中使用 $(this) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13416205/

相关文章:

javascript - 如何处理同一个表单中多个Jquery + Ajax依赖的选择框

javascript - Jquery 向上滑动登录表单

javascript - 将一些 html 代码分解为对象数组

php - 如果选择了特定类别,则在管理帖子页面上显示一些内容

jquery - Bootstrap "buttons-radio"使用 AngularJS 切换

jquery - 将 Ajax 与 jQuery DataTables 结合使用时,如何确定如何处理返回的数据?

javascript - 在 PHP 中如何使用 $_REQUEST 检索输入数组以输入数据库

javascript - jQuery 可以转到另一个页面,抓取 10 个链接,并在第一页上使用它们吗?

javascript - 改变不同实例(不是所有实例)的 ckeditor 维度

javascript - 如何使用动态 data-websockets 运行 AngularJS 服务