Javascript 如何将jQuery输出存储到全局变量中

Javascript 如何将jQuery输出存储到全局变量中,javascript,jquery,Javascript,Jquery,请参阅下面的代码- $(function() { $.fn.getPosition = function() { var results = $(this).position(); results.right = results.left + $(this).width(); results.bottom = results.top + $(this).height(); return results; } $(".drag")

请参阅下面的代码-

 $(function() {
  $.fn.getPosition = function() {
    var results = $(this).position();
    results.right = results.left + $(this).width();
    results.bottom = results.top + $(this).height();
    return results;
  }

  $(".drag").draggable({
    containment: "parent",
    stop: function(e, ui) {
      console.log($(this).attr("id"), $(this).getPosition());
    }
  });
});

请原谅noob的问题,但是我如何将
.getPosition()
的输出存储到一个全局变量中,以便在其他函数中使用,而不是
console.log($(this).attr(“id”),$(this.getPosition())

在全局范围内声明一个新变量。然后在其他方法中也使用它

在以下代码段中更新:

 let positionValue;
 $(function() {
  $.fn.getPosition = function() {
    var results = $(this).position();
    results.right = results.left + $(this).width();
    results.bottom = results.top + $(this).height();
    return results;
  }

  $(".drag").draggable({
    containment: "parent",
    stop: function(e, ui) {
      positionValue = $(this).attr("id"), $(this).getPosition();
    }
  });
});

您可以首先在文件顶部声明一个全局变量。(正如你帖子下面的评论所说)


只需在之前声明一个全局变量,并在希望赋值的位置使用它:

var yourVariable; // <-- declare here

$(function() {
  $.fn.getPosition = function() {
    var results = $(this).position();
    results.right = results.left + $(this).width();
    results.bottom = results.top + $(this).height();
    return results;
  }

  $(".drag").draggable({
    containment: "parent",
    stop: function(e, ui) {
      console.log($(this).attr("id"), $(this).getPosition());
      yourVariable = $(this).getPosition();     // <-- assign here
    }
  });
});

var变量;//在js文件的顶部标记一个变量,并为该变量指定位置<代码>var位置=”position=$(this.getPosition()在另一个函数中调用它之前尝试过的表示未定义\在另一个函数中调用它之前尝试过的表示未定义只有在触发事件时才会初始化,因为它是在该特定事件的回调函数中提供的。我想,这是一个拖停事件。如果需要默认值,可以在变量声明本身上初始化它<代码>让位置值=某个值
var yourVariable; // <-- declare here

$(function() {
  $.fn.getPosition = function() {
    var results = $(this).position();
    results.right = results.left + $(this).width();
    results.bottom = results.top + $(this).height();
    return results;
  }

  $(".drag").draggable({
    containment: "parent",
    stop: function(e, ui) {
      console.log($(this).attr("id"), $(this).getPosition());
      yourVariable = $(this).getPosition();     // <-- assign here
    }
  });
});