首页 > 解决方案 > 函数不是 onClick 中的函数

问题描述

我试图从每个 tr 调用一个内置函数,当它被点击时。但我得到一个错误Uncaught TypeError: this.updateSelection is not a function at HTMLTableRowElement.onclick (index.html:1)

在这里,我渲染了我的 HTML 模板。

    this.renderHtml = function () {
        return '<div class="widget-content widget-infotablewidget">' + 
                '<div class="infotable"></div>' +
        '</div>';
    };

当某些条件通过时,我会渲染一个表格。

this.updateTable = function (rows) {
        let appendix = '<table><thead><tr>';
        for (let i = 0; i < Object.keys(rows[0]).length; i++) {
            appendix += '<th>' + Object.keys(rows[0])[i] + '</th>';
        }

        appendix += '</tr></thead><tbody>';

        for (let i = 0; i < rows.length; i++) {
            appendix += `<tr onclick="this.updateSelection(\'InfoTable\', ${i})">`;

            for (let cell in rows[i]) {
                appendix += '<td>' + rows[i][cell] + '</td>';
            }
            appendix += '</tr>';
        }

        appendix += '</tbody></table>';
        valueElem.append(appendix);
    }

我希望该函数能够更新选择,但会出错。

标签: javascripthtmldom

解决方案


实际上,解决问题的最简单方法是定义var thisInstance = this;和使用withInstance.updateSelection不与不同的范围冲突。


推荐阅读