簡體   English   中英

存儲一個事件處理程序中的變量以供另一事件處理程序使用

[英]Store variable from one event handler to be used by another event handler

我有以下代碼:

$("#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);
});

文件

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");
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM