简体   繁体   中英

$(window) not being recognised as a window

I am trying to write a function that recognises if a javascript variable is the window. I have researched some ways to find out if a variable is the window but none seem to be working.

I have tried the following

  //define the variable as the window
  var myVariable  =$(window);


 //attempt 1 by comparing variable to window - showing not a window
 if(myVariable==window){
    console.log("window");
 }
 else{
    console.log("not a window"); 
 }

 //attempt 2 - showing not a window
 if(myVariable===window){
    console.log("window");
 }
 else{
    console.log("not a window"); 
 }

  //atttempt 3   - returns false - from https://stackoverflow.com/questions/9576283/jquerys-iswindow-method
  function isWindow(obj) {
        var toString = Object.prototype.toString.call(obj);
         return toString == '[object global]' || toString == '[object 
         Window]' || toString == '[object DOMWindow]';
  }

  ///attempt 4 - returns false
   function isWindowf(obj) { return ['[object global]','[object 
          Window]','[object DOMWindow]'].indexOf(Object.prototype.toString.call(obj)) >= 0
 }

I am looking for a function that I can put a variable into and it will say whether the variable is the window eg

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 <script>
 //define the variable
 var myVariable=$(window);

 //put the variable into a function
 function checkIfMyVariableIsAWindow(myVariable  ){
     //if is a window then return true    
     if(/*code to run to see if is a window*/){ 
            console.log("is a window")
      }
      //if not a window then return false
      else{
           console.log("is not a window")
      }   
  }
  <script>

Thanks in advance for your help

Try using myVariable[0] , jQuery by default returns the array of DOM elements.

jQuery by default returns the array of DOM elements, you have to use the first element of the array to access the DOM

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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