从属性获取父对象属性

时间:2018-06-16 21:44:19

标签: arrays properties parent

我制作了以下名为Tabs

的对象类
class Tabs {
// Create constructor
constructor() {
    // Set rules for number of arguments
    if(arguments.length == 0) {
        var msg = "Tabs requires id (and parentId) as "
            + "arguments";
        throw new Error(msg);
    } else if(arguments.length == 1){
        var msg = "Tabs assumes that parent is document." + "body";
        console.warn(msg);
        this.id = arguments[0];
        this.parentId = "document.body";
    } else {
        this.id = arguments[0];
        this.parentId = arguments[1]
    }

    // Set parent of Tabs instance
    if(this.parentId == "document.body") {
        document.body.append(this.tab);
    } else {
        var el = document.getElementById(this.parentId);
        el.append(this.tab);
    }
    // Define array for storing tab button information
    this.tabs = [];
}

// Ada label for tab button
addTab(label) {
    // Avoid same tab label
    var ilabel = this.tabs.indexOf(label);
    if(ilabel < 0) {
        this.tabs.push(label);
    } else {
        var msg = "Duplicate label " + label + " is igonered";
        console.warn(msg);
    }
    var N = this.tabs.length;
    for(var i = 0; i < N; i++) {
        var id = this.id + this.tabs[i];
        var btn = document.getElementById(id);
        if(btn == undefined) {
            var btn = document.createElement("button");
            btn.id = id;
            btn.className = this.tablinkscs;
            btn.innerHTML = this.tabs[i];
            btn.addEventListener("click", this.toggleContent)
            this.tab.append(btn);
        }
    }
    this.updateTabButtonsWidth();
}

和事件处理程序toggleContent

// Toggle tab content when button clicked
toggleContent() {
    // https://www.w3schools.com/howto/howto_js_tabs.asp

    var parent = event.target.parentElement;
    console.log(parent);
..
}

我尝试使用Tabs访问this属性,但父级已经是触发click事件的按钮。

有没有办法使用Tabs访问this属性,因为button的父级是divdiv的父级是{{1}而不是document.body

0 个答案:

没有答案