首页 > 解决方案 > 我可以在 html 中的一个脚本中有 2 个函数吗?

问题描述

我的页面有一个显示不同数据的多个“选项卡”。

这是我的标签功能。

function openEvt(evt, evtName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(evtName).style.display = "block";
    evt.currentTarget.className += " active";
}

当用户单击“详细信息”选项卡时,我的页面将显示条形图。这是我的图表代码。我用函数 openEvt() 把它放在脚本中。

function setChart(){
    var ctx = document.getElementById("detail");

    var detail= new Chart(ctx, {
    type: 'bar',
    data: {
        labels: {{ chartdata_labels|safe }},
        datasets: [{
            label: '# of votes',
            data: {{ chartdata_data }},
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
}

window.onload = setChart;

这是我在数据表上方显示图表的代码。

<canvas id="detail" width="1200" height="400"></canvas>

当只有一个函数-openEvt() 时,它可以正常工作。但是当我在 setChart() 中添加时,该选项卡将不起作用并且没有任何数据显示。

标签: javascripthtml

解决方案


function SayHello() {
    alert('Hello')
}
function SayWorld() {
    alert('World')
}

function addWindowOnloadEvent(func) {
    var oldWindowOnload = window.onload;
    if (typeof func === 'function') {
        if (typeof window.onload === 'function') {
            window.onload = function () {
                oldWindowOnload();
                func();
            }
        } else {
            window.onload = func;
        }
    }
}

addWindowOnloadEvent(SayHello);
addWindowOnloadEvent(SayWorld);

推荐阅读