2016-02-01 43 views
1

打字稿中完全是新手。我只是試圖找到一個選擇器的元素。無論我嘗試findElement()方法總是不確定。我在哪裏做錯了? 任何幫助非常感謝!試圖在打字稿上找到DOM上的元素

var cdnBasePath: any = this.findElement('meta[name="cdnBasePath"]').attr('content'); 

public findElement(selector: any) { 

      if (angular.isDefined(this.$window.jQuery)) { 
       return this.$document.find(selector); 
      } else { 
       return angular.element(this.$document.querySelector(selector)); 
      } 

     } 
+1

嘗試跟蹤Firefox/Chrome控制檯中的JavaScript執行情況。 –

回答

1

爲了定義「this」,你必須聲明你的findElement作爲某個類的實例方法。就像這樣:

class SomeClass 
{ 
    public SomeMethod() 
    { 
     var cdnBasePath: any = this.findElement('meta[name="cdnBasePath"]').attr('content'); 
    } 

    public findElement(selector: any) 
    { 
     if (angular.isDefined(this.$window.jQuery)) { 
      return this.$document.find(selector); 
     } else { 
      return angular.element(this.$document.querySelector(selector)); 
     } 
    } 
} 

否則,你可以把它作爲靜態方法:

class UI 
{ 
    public static findElement(selector: any) 
    { 
      if (angular.isDefined(this.$window.jQuery)) { 
       return this.$document.find(selector); 
      } else { 
       return angular.element(this.$document.querySelector(selector)); 
      } 
    } 
} 

var cdnBasePath: any = UI.findElement('meta[name="cdnBasePath"]').attr('content'); 

或者剛落,「這個」,並將它作爲全局函數(我不建議這樣做)

function findElement(selector: any) 
{ 
    if (angular.isDefined(this.$window.jQuery)) { 
     return this.$document.find(selector); 
    } else { 
     return angular.element(this.$document.querySelector(selector)); 
    } 
} 

var cdnBasePath: any = findElement('meta[name="cdnBasePath"]').attr('content'); 

希望這有助於。