存储一个事件处理程序中的变量以供另一个事件处理器使用



我有这个代码:

$("#open").click(function()
{
 var pos = $(window).scrollTop();
 /* the next lines of code affects the value
  * of 'pos'.
  */
});
$("#close").click(function()
{
 var pos = /* what i want here is the $(window).scrollTop(); 
            before the #open event handler changes it's value. */
 //another code of mine.
});

有人能帮我吗?提前谢谢。

这很简单,使变量全局

var pos; //global variable
$("#open").click(function()
{
 pos = $(window).scrollTop();
 /* the next lines of code affects the value
  * of 'pos'.
  */
});
$("#close").click(function()
{
 // use pos here accordingly
 //another code of mine.
});

您可以在调用任何函数之前存储原始window DOM内容:

var pos;
$("#open").click(function(){
    pos = $(window).scrollTop();
});
$("#close").click(function(){
    $(window).height(pos);
});

文档

  • http://api.jquery.com/scrollTop/
  • http://api.jquery.com/height/
You could just organize a little your code and do this:
function MyApp(){
   var self = this;
   this.pos = "";
   this.temp = $(window).scrollTop();   //store initial value 
   this.wire = function(){
      $("#open").click(self.open);
      $("#close").click(self.close);
   }
   this.open = function(){
     self.pos = $(window).scrollTop();
      /* the next lines of code affects the value
       * of 'pos'.
       */
   }
   this.close = function(){
     self.pos = /* what i want here is the $(window).scrollTop(); before
            * the #open event handler changes it's value.
            */
        //another code of mine.
     var original = self.temp;  //here get the initial stored value
   }

}

示例:

<script type="text/javascript">
    $(function() {
        var app = new MyApp();
        app.wire();         //wire handlers
    });
</script>

我会使用一个匿名函数的本地变量:

(function() {
    var context = {};
    $('#open').click(function() {
        context.pos = $(window).scrollTop();
    });
    $('#close').click(function() {
        // Do something with context.pos
    });
})();

您的代码和解释并没有明确说明这一点,但以上内容保留了代码中的一个假设:除非单击了打开,否则无法单击关闭;除非单击了关闭,否则无法再次单击打开。但这实际上取决于你的代码——如果这个假设不成立,我会采取不同的方法(如果这个假设不是真的,点击此处关闭可能会得到一个未定义的)。

更安全的方式。

 $("#open").click(function() {
            $("#close").attr("data-pop", $(window).scrollTop());
        });
        $("#close").click(function() {
            var pos = $(this).attr("data-pop");
        });

相关内容

最新更新