2012-09-22 3 views
0

2 개의 jquery 함수가 있습니다. 첫 번째 변수에서 두 번째 변수까지 전달하고 싶습니다. 내가 읽은 것에서 나는 변수를 전역 변수로 설정할 필요가 있지만, 내가 읽고 재현하려고하는 메소드는 작동하지 않는 것처럼 보입니다.다른 함수에 변수 전달

$(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);   
      }); 
  • 나는 이런 식으로하려고 노력했다 :

첫 번째 방법는 - 여기에 본 : http://www.quirksmode.org/js/function.html

변수 설정 : 예 (인덱스);

변수 검색 중 : function example (a) {index = a};

이것은 작동하지 않습니다. $ .post에 변수로 인덱스를 포함하려고하면 함수가 작동하지 않습니다.

이 방법에 대한 두 번째 방법은 충분히 인식하지,하지만이 솔루션처럼 보인다, 완전히 이해하는 경우 : document.write를()를 -하지만 난 다시 검색하는 방법을 알아 갈 수없는 것.

누군가가 이것에 대한 해결책을 가지고 있습니다. 나는 다음 일에이 간단한 것을 넘어 가기 위해 많은 노력을했습니다.

미리 감사드립니다.

내가 잘 이해하면
+0

당신은 첫 번째 함수에 '# 슬라이더 범위'에 사용자 정의 속성을 추가, 두 번째에 하나 –

+0

당신이 var에 PARAM를 선언 얻을 수 있습니다 (기술적으로도이 같은 window.param 것) 당신이 호출하는 경우 두 번째 함수는 첫째로이 매개 변수가 '언더 파인드'가 될 것입니다. 하지만 첫 번째 함수를 호출하면 두 번째 이후에이 매개 변수를 얻을 수 있습니다. –

+0

. 서 준비 호출 외부의 색인을 설정하고 두 개의 .D 준비 호출을 하나로 결합하십시오. – j08691

답변

0

당신은 범위가 지정되지 않은 변수를 사용하여이에게 방법의 수를 할 수있는,하지 않는 것이 좋습니다! ...

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

}); 

이 두 문서 준비 인클로저를 병합하고 내에서 변수를 범위 지정 ...

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

}); 

또는 데이터 속성으로 함께 전달하여 ...

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

}); 

또한 그것을 포장 할 수 인클로저 또는 익명 함수 내에서 인스턴스 속성을 사용하거나 범위를 지정합니다.

휴식 방법에 대한 자세한 내용은 좋을 것입니다. 값이 예상대로 (예 :

$(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);   
     }); 
    } 
    }); 
}); 
+0

안녕 스튜어트. 정말 도움이 되었어요. 정말 위대한 답을 주셨고 제게 많은 것을 가르쳐 주셨습니다. – Niels

+0

기꺼이 도와 드리겠습니다. –

0

...

당신은 찾아 볼해야 자바 스크립트 더 많은 범위에서, 더 전진 할 시간입니다 것을 알 ... 당신이 개 기능의 첫 번째 공통 범위에서 전역 변수를 정의해야 ...

$(function() { 

    var globalVar = ''; 

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

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

답변 해 주셔서 감사합니다. – Niels

2

음 소모, 나는 보통 더 우아, 네임 스페이스의 사용을 선호하고, 당신은 페이지의 아무 곳이나 변수에 참조 할 수 있습니다.

내가 일반적으로 사용하는 설정은 다음과 같이이다 :

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(); 

이 구조는 다른 스크립트 참조에 대한 코드 청소기 쉽게한다.

+0

안녕하세요 Nicolini. 네, 그렇지 않으면 그것을 구축하는 것이 의미가 될 것을 알 수 있습니다, 나는 (또는) 변수를 변경하여 init를 원하기 때문에 구조를 변경하고 싶을 수도 있습니다. 기여 해줘서 고마워! – Niels

관련 문제