2013-04-07 153 views
0

我想創建一個jQuery彈出腳本OO風格。我這樣做是因爲我想用更多的jquery/javascript擴展這段代碼而不會丟失疏忽。我收到的錯誤是Object #<HTMLDivElement> has no method 'centerPopup'Resource interpreted as Script but transferred with MIME type text/x-c:我是新來OO的Javascript,但在面向對象PHP頗有經驗使用jQuery與OO Javascript

function popup(){ 

    var popupStatus = 0; 

    $(document).ready(function() { 
     $("#button").click(function() 
     { 
      this.centerPopup(); 
      this.loadPopup(); 
     }); 

     $("#backgroundPopup").click(function() 
     { 
      this.disablePopup(); 
     }); 

     $(document).keypress(function(e) 
     { 
      if(e.keyCode==27 && popupStatus==1) 
      { 
       this.disablePopup(); 
      } 
     }); 

    }); 

     this.loadPopup = function(){ 
     if(this.popupStatus==0) 
     { 
      $("#backgroundPopup").css(
      { 
       "opacity": "0.7" 
      }); 
      $("#backgroundPopup").fadeIn("slow"); 
      $("#popupContact").fadeIn("slow"); 

     this.popupStatus = 1; 
     } 
    } 

    this.disablePopup = function(){ 
     if(this.popupStatus==1) 
     { 
      $("#backgroundPopup").fadeOut("slow"); 
      $("#popupContact").fadeOut("slow"); 
      this.popupStatus = 0; 
     } 
    } 

    this.centerPopup = function(){ 
     var windowWidth = document.documentElement.clientWidth; 
     var windowHeight = document.documentElement.clientHeight; 
     var popupHeight = $("#popupContact").height(); 
     var popupWidth = $("#popupContact").width(); 

     $("#popupContact").css(
     { 
      "position": "absolute", 
      "top": windowHeight/2-popupHeight/2, 
      "left": windowWidth/2-popupWidth/2 
     }); 

     $("#backgroundPopup").css(
     { 
      "height": windowHeight 
     }); 
    } 
} 

var popup = new popup() 


<!DOCTYPE HTML> 

<html> 
<head> 
<link rel="stylesheet" href="css/popup.css" type="text/css" media="screen" /> 
<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript"></script> 
<script src="js/popup2.js" type="text/javascript"></script> 
</head> 
<body> 

    <center> 
     <div id="button"><input type="submit" value="Popup!" /></div> 
    </center> 

    <div id="popupContact"> 
     <a id="popupContactClose">x</a> 
    </div> 

    <div id="backgroundPopup"></div> 

</body> 
</html> 
+0

可能重複[Overwrite「this」variable problem or how to call a member function?](http:// stackoverflow。 COM /問題/ 737454 /覆蓋,這個值變量問題或知識到呼叫一個成員函數) – 2013-04-07 17:40:57

回答

2
$("#button").click(function() 
     { 
      this.centerPopup(); 
      this.loadPopup(); 
     }); 

this是不是你實際上想。這不是popup的實例,而是DOM元素(#button)。您可以通過在您的課程開始時在您的實例上保存一個參考來解決此問題:

function popup(){ 
    var self = this; 
    this.popupStatus = 0; // you should use `this` here 

    $(document).ready(function() { 
     $("#button").click(function() 
     { 
      self.centerPopup(); 
      self.loadPopup(); 
     }); 
/* ... snip ... */