1

我的文档中有一些包含图像 ID 的元素,我想用图像替换这些 ID:

$(".image_id_field").each(function() {
  img_id = $(this).html();

  $.post("ajax/get_image.php", { id: img_id }, function( response) {
    // data = "<img src='path_to_image.png' />"
    // How is it possible, to get the current $(this) in here to append the response
  });
)

我有两个想法:

1.是否可以从success函数中的post参数中获取给定的id来识别元素?

2. 是否可以让 $post 异步并在触发 post 请求后使用响应?

4

1 回答 1

0

定义函数时,函数会记住其父作用域中的变量。这称为闭包。你可以在这里阅读

因此,为了保留对元素的引用,请将元素存储在变量中,如下所示:

$(".image_id_field").each(function() {
    var $this = $(this), // store the jQuery element
        img_id = $this.html();

    $.post("ajax/get_image.php", { id: img_id }, function( response) {
        // the callback function still references the $this var defined in the parent scope
        $this.html(response);
  });
)

我不确定您的第二个问题,因为 $.post 调用已经是异步的。

我建议您更详细地了解变量范围,因为在您的示例中,您正在创建一个名为img_id. JavaScript 中变量的作用域是什么?

于 2013-11-08T12:39:05.813 回答