Programing

jQuery.ready에 정의 된 함수를 전역 적으로 사용하려면 어떻게해야합니까?

lottogame 2020. 11. 17. 07:39
반응형

jQuery.ready에 정의 된 함수를 전역 적으로 사용하려면 어떻게해야합니까?


URL에서 YouTube ID를 제거하는 기능이 있습니다. 그런 다음이 기능을 페이지 당 10 번 사용하고 싶습니다 (wordpress 루프에서).

함수 스크립트 태그 내에서 URL을 입력하면 함수가 잘 작동하지만 루프 내에서 새로운 스크립트 태그 세트를 시작하면 작동하지 않습니다.

먼저 모든 것을 선언하지 않고 함수를 어떻게 사용할 수 있는지 알아야합니다.

그래서 이것은 헤더에있는 코드입니다.

 <script type="text/javascript"> 
$(document).ready(function() {
var getList = function(url, gkey){
        var returned = null;
        if (url.indexOf("?") != -1){
          var list = url.split("?")[1].split("&"),
                  gets = [];

          for (var ind in list){
            var kv = list[ind].split("=");
            if (kv.length>0)
                gets[kv[0]] = kv[1];
        }

        returned = gets;

        if (typeof gkey != "undefined")
            if (typeof gets[gkey] != "undefined")
                returned = gets[gkey];

        }

            return returned;

    };


        // THIS WORKS

    alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));


      });

그러나 페이지의 다른 곳에서 이것을 사용하려고하면 작동하지 않습니다.

 <script type="text/javascript"> 

      $(document).ready(function() {
              alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));
      };
      </script>

Firebug는 getList가 정의 되지 않았기 때문에 의미가 없습니다. 이 함수를 '전역 적으로'선언 할 수 있습니까?


두 가지 옵션이 있습니다. window객체에 추가 하여 전역으로 만듭니다.

window.getList = function(url, gkey){ 
    // etc...
}

또는 문서 준비 이벤트 핸들러 내부에서 전역 범위로 이동합니다.

$(document).ready(function() {  
    alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));
});  
var getList = function(url, gkey){  

    var returned = null;  
    if (url.indexOf("?") != -1){  
      var list = url.split("?")[1].split("&"),  
              gets = [];  

      for (var ind in list){  
        var kv = list[ind].split("=");  
        if (kv.length>0)  
            gets[kv[0]] = kv[1];  
    }  

    returned = gets;  

    if (typeof gkey != "undefined")  
        if (typeof gets[gkey] != "undefined")  
            returned = gets[gkey];  

    }  

        return returned;  

};  

You might also want to read this question about using var functionName = function () {} vs function functionName() {}, and this article about variable scope.


Yet another option is to hang the function off the jQuery object itself. That way you avoid polluting the global name space any further:

jQuery.getlist = function getlist(url, gkey) {
  // ...
}

Then you can get at it with "$.getlist(url, key)"


declare getList() outside the ready() function..

var getList = function(url, gkey){
        var returned = null;
        if (url.indexOf("?") != 
....
....
...
};

Now the getList will work anywhere in the code:

$(document).ready( function() {
alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));
});

The problem was, scope of the getList(.) function.


Just define it as a regular function at the top of your script:

<script type="text/javascript">
    function getlist(url, gkey){  
        ...
    }
</script>

You can simply add your function in the $.fn variable:

(function ($) {

   $.fn.getList = function() {
       // ...
   };

}(jQuery));

Example usage:

$().getList();

This is what you would typically do while creating a Basic Plugin for jQuery.


To declare it as a global function, just get rid of all the jQuery specific bits. Something like this:

function getList(url, gkey) {
    var returned = null;
    if (url.indexOf("?") != -1){
    var list = url.split("?")[1].split("&"), gets = [];
    for (var ind in list){
        var kv = list[ind].split("=");
        if (kv.length>0) {
            gets[kv[0]] = kv[1];
        }
    }

    returned = gets;

    if (typeof gkey != "undefined") {
        if (typeof gets[gkey] != "undefined") {
            returned = gets[gkey];
        }
    }

    return returned;
}

And then you should be able to call it from anywhere.

참고URL : https://stackoverflow.com/questions/2223305/how-can-i-make-a-function-defined-in-jquery-ready-available-globally

반응형