Angularjs 尝试使用typescript在DOM上查找元素

Angularjs 尝试使用typescript在DOM上查找元素,angularjs,typescript,selector,element,Angularjs,Typescript,Selector,Element,我完全是打字新手。我只是想找到一个带有选择器的元素。无论我尝试了什么,findElement()方法总是变成未定义的。我哪里做错了? 非常感谢您的帮助 var cdnBasePath: any = this.findElement('meta[name="cdnBasePath"]').attr('content'); public findElement(selector: any) { if (angular.isDefined(this.$window.jQue

我完全是打字新手。我只是想找到一个带有选择器的元素。无论我尝试了什么,findElement()方法总是变成未定义的。我哪里做错了? 非常感谢您的帮助

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

        }
为了定义“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');
或者干脆删除“this”并将其作为全局函数(我不建议这样做)


希望这有帮助。

尝试在Firefox/Chrome控制台中跟踪JavaScript执行情况。
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');