简体   繁体   English

将变量传递给另一个函数

[英]Passing a variable to another function

I got 2 jQUERY functions - and i want to pass a variable from the first to the second. 我有2个jQUERY函数 - 我想从第一个到第二个传递一个变量。 From what i read i need to set the variable as a global variable, but the methods i read and try to reproduce doesn't seem to work. 从我读到的我需要将变量设置为全局变量,但我阅读并尝试重现的方法似乎不起作用。

    $(function() {
        $("#selectable").selectable({
            stop: function() {
            $(".ui-selected", this).each(function() {
            var index = $("#selectable li").index(this); });}});});

    $(function() {
    $("#slider-range").slider({
        range: true,
        min: 0,
        max: 180,
        values: [0, 180],
            slide: function(event, ui) {
            var result = $("#result").empty();
            var low = (ui.values[0]);
            var high = (ui.values[1]);
            HERE I NEED THE VARIABLE FROM THE ABOVE FUNCTION

            $.post('search.php',{low: (ui.values[0]), high: (ui.values[1]), HERE I NEED VARIABLE FROM THE ABOVE FUNCTION},
            function(data){
            result.append(data);        
            }); 
  • I have tried to do like this: 我试过这样做:

FIRST METHOD - Seen here : http://www.quirksmode.org/js/function.html 第一种方法 - 见此处: http//www.quirksmode.org/js/function.html

setting variable : example(index); 设置变量:example(index);

retrieveing variable : function example(a) {index = a}; 检索变量:function example(a){index = a};

This i can't get to work.. the functions breaks when i try to include the index as the variable in the $.post. 我无法工作..当我尝试将索引作为$ .post中的变量包含时,函数会中断。

SECOND METHOD Not fully aware about this method, but this seems like a solution, if fully understood: document.write() - But i can't seem to get to know how to retrieve it again. 第二种方法不完全了解这种方法,但这似乎是一个解决方案,如果完全理解:document.write() - 但我似乎无法知道如何再次检索它。

Hope somebody has a solution for this as i have had tried a load of things to try to pass this rather simple thing on to the next function. 希望有人有一个解决方案,因为我已经尝试过一些东西试图将这个相当简单的事情传递给下一个函数。

Thanks in advance. 提前致谢。

Well, I usually prefer the use of Namespaces , it's more elegant, and you can reference to the variable anywhere on the page. 好吧,我通常更喜欢使用命名空间 ,它更优雅,你可以在页面的任何地方引用变量。

The setup I normally use is like this: 我通常使用的设置是这样的:

var Namespace = (function() {

    return {

            /**
            * Initialize the page. 
            */
            init: function() {

                  //Here you can set Global Variables 
                  //inside the Namespace using "this"
                  this.variable1 = true;
                  this.variable2 = false;

                  //You may call other functions
                  this.setListeners();

            },

            setListeners() {

                  //You may reference the variables using "this"
                  if(this.variable1 == true) {
                      alert(this.variable2);
                  }
            },

            otherFunction() {

                  //When calling functions with callbacks, 
                  //you should set a variable inside the function 
                  //so you may use that in the callbacks to the namespace
                  var self = this;

                  $("#target").click(function() {
                     //Now you can use the variable self in the callbacks
                     alert(self.variable1);

                     //Or you may also use the namespace
                     alert(Namespace.variable1);
                  });
            }
      };
})();

$(document).ready(function(){
         //Here you may call the init function which should fire 
         //everything else you need in the page load
         Namespace.init();
});

//You may also use the variables anywhere else in the page 
//or in other Javascript files by referencing to the namespace

//Variable
Namespace.variable1;
Namespace.variable2;

//Function
Namespace.otherFunction();

This structure makes the code cleaner and easy to reference by other scripts. 此结构使代码更清晰,并且易于通过其他脚本引用。

If I well understood ... 如果我很好理解......

You have to define a global variable in the first common scope of your 2 functions ... Notice that the more scopes javascript should look up, the more the precess is time consuming ... 你必须在你的2个函数的第一个共同范围中定义一个全局变量...请注意,javascript应该查找的范围越多,进程越耗时...

$(function() {

   var globalVar = '';

   $("#selectable").plugin1({callback:function() {
         // you have access to globalVar
   }});

   $("#slider-range").plugin2({callback:function() {
         // you have access to globalVar
   }});
});

You could do this any number of ways, using an unscoped variable, not recommended!... 您可以使用未编码的变量以任意数量的方式执行此操作,不建议使用!...

$(function() {

  $("#selectable").selectable({
    stop: function() {
      $(".ui-selected", this).each(function() {
        index = $("#selectable").index(this);
      });
    }
  });

});

$(function() {

  $("#slider-range").slider({
    slide: function() {
      // Might want to check index is set as is might not have
      // been set yet
      $.post("search.php", {low: x, high: y, index: index}, function() {
        // Do something
      });
    }
  });

});

Merging your two document ready enclosures and scoping a variable within... 合并两个文档就绪的机箱并在一个变量范围内...

$(function() {

  var index;

  $("#selectable").selectable({
    stop: function() {
      $(".ui-selected", this).each(function() {
        index = $("#selectable").index(this);
      });
    }
  });

  $("#slider-range").slider({
    slide: function() {
      // Might want to check index is set as is might not have
      // been set yet
      $.post("search.php", {low: x, high: y, index: index}, function() {
        // Do something
      });
    }
  });

});

Or by passing it along as a data attribute... 或者将其作为数据属性传递...

$(function() {

  $("#selectable").selectable({
    stop: function() {
      $(".ui-selected", this).each(function() {
        $("#selectable").data("index", $("#selectable").index(this));
      });
    }
  });

  $("#slider-range").slider({
    slide: function() {
      var index = $("#selectable").data("index");
      // Might want to check index is set as is might not have
      // been set yet
      $.post("search.php", {low: x, high: y, index: index}, function() {
        // Do something
      });
    }
  });

});

You could also wrap it within an object and use an instance property, or scope it within an enclosure or anonymous function. 您还可以将其包装在对象中并使用实例属性,或将其范围限定在机箱或匿名函数中。

Giving details on how it breaks would be good. 详细说明它如何破坏会很好。 You might want to check that the value is as you expect it, ie 您可能想要检查该值是否符合您的预期,即

$(function() {
  $("#selectable").selectable({
    stop: function() {
      $(".ui-selected", this).each(function() {
        index = $("#selectable li").index(this);

        // Check the index after the selection
        console.log("Selected index " + index);
      });
    }
  });
});

$(function() {
  $("#slider-range").slider({
    range: true,
    min: 0,
    max: 180,
    values: [0, 180],
    slide: function(event, ui) {

      var result = $("#result").empty();
      var low = (ui.values[0]);
      var high = (ui.values[1]);

      // Check the index before the post
      console.log("Slide index " + index);        

      $.post('search.php', {
          low: ui.values[0], 
          high: ui.values[1], 
          index: index
        }, 
        function(data){
          result.append(data);        
        }); 
    }
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM