TypeError:this.getAttribute不是一个函数-javascript

TypeError: this.getAttribute is not a function - javascript

本文关键字:一个 函数 -javascript this getAttribute TypeError      更新时间:2023-09-26

我不明白为什么我不能在下面的代码中获得"this"的属性:

var Deferjs = {
init: function(){
    if(document.getElementById('js-currentPage')!=null){
        var file = this.getAttribute('data-page');
        Deferjs.LoadJs(file);
    }
},
LoadJs:function(file){
    alert("ok");
}
}
Deferjs.init();

但是,如果我改变this.getAttribute('data-page');到document.getElementById('jscurrentPage').getAttribute它工作于

请帮助我理解以上

thx

如果要重用document.getElementById('js-currentPage'),请将其保存在变量中。在this指向容器对象(DeferJs)的情况下,不能用this引用它

init: function(){
    var elem=document.getElementById('js-currentPage');
    if(elem!=null){
        var file = elem.getAttribute('data-page');
        Deferjs.LoadJs(file);
    }
}
if(document.getElementById('js-currentPage')!=null){
        var file = this.getAttribute('data-page');

这里this将指代Deferjs。相反,如果要在其他位置访问变量,则必须将对DOM的引用存储到该变量。

   var ele = document.getElementById('js-currentPage');
   if(ele!=null){
            var file = ele.getAttribute('data-page');

您的init函数位于Deferjs中,因此,当您使用"this"时,它指的是Deferjs。Deferjs没有名为getAttribute的函数。你需要使用

document.getElementById('js-currentPage').getAttribute(...)

DOM 实际上提供了一组API来访问HTML元素,并且这个指针指向对象的范围,该对象只能访问属性>类、ID、样式等。

在对象的作用域中,也就是说,您可以通过对象属性访问(this.data-message)。但是,在对象的范围中有没有getAttribute()方法,所以您不能使用this.getAttribute(