0

考虑这个片段:

$('.job-details-apply').live('click', function () {
    var url = $('#apply-job-url').val();
    var id = $(this).attr('value');
    var selected = $(this);
    $.ajax({
        url: url,
        data: { id: id },
        success: function (data) {
            $(selected).html('Test!');//selected is undefined at this point
        },
        error: function () {
        }
    });
    return false;
});

var selected成功处理程序中未定义。我是否需要将其范围限定在点击功能之外?例如

var selected = null;
$('.job-details-apply').live('click', function () {
    selected = $(this);
    //blah
}

对我来说,这似乎有些不对劲。

编辑:如果从控制器 id a 返回的值有所不同JsonResult(目前它只是一个布尔值)

4

3 回答 3

3

您无需更改selected变量的声明方式。它将在您的 ajax 函数的成功处理程序中可用。

作为 jQuery ajax 成功处理程序中偶尔混淆的一点,但不是导致此问题的原因,this您的 ajax 成功处理程序中的值会有所不同(它将指向一个 ajax 对象),但这不会影响对变量的访问在您的父函数中声明,因为它们可以直接使用而无需使用this.

所以,既然你问的不是问题,如果你确实对selected变量有问题,那么原因一定是你在到目前为止显示的代码中没有向我们透露的其他原因。我们可能需要查看更完整的示例来说明您遇到此问题的位置,甚至是指向工作页面的链接,以便可以设置断点并检查内容。

于 2012-08-25T02:16:57.890 回答
0

When you do

var selected = $(this);

selected is now a jQuery object built from the element you clicked (this is the DOM object for the element you clicked; it doesn't have any jQuery methods; selected does get jQuery methods).

$.ajax({
    url: url,
    data: { id: id },
    success: function (data) {
        $(selected).html('Test!');//selected is undefined at this point

selected should certainly be defined at this point, since it's an outer variable incorporated into a closure. However, $(selected) resolves to an attempt to pass what's already a jQuery object into a jQuery constructor, and jQuery is probably getting a little confused, since a jQuery constructor is generally expecting to see a DOM object (convert to jQuery object), an HTML string (build a corresponding DOM fragment and convert to jQuery object), a function (run it when the DOM is loaded), or an extended CSS selector (convert it into a jQuery object that represents one or more elements in the page). So the result of $(selected) isn't officially defined.

Obviously if this is the source of the problem, changing the code to selected.html(...) should at least give a different result, and should preferably work. },

于 2012-08-25T09:06:36.813 回答
-1

是的,需要存储this在一个变量中。

$('.job-details-apply').live('click', function () {
  var url = $('#apply-job-url').val();
  var id = $(this).attr('value');
  var _this = this;
  $.ajax({
      url: url,
      data: { id: id },
      success: function (data) {
          $(_this).html('Test!');
      },
      error: function () {
      }
  });
  return false;
});
于 2012-08-25T02:27:54.283 回答