简体   繁体   中英

Can i have 2 function in one script in html?

My page has a multiple 'tab' which displaying different data.

Here is my function for tab.

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

My page will display a bar chart when user click 'Detail' tab. This is my code for the chart. I put it in the script with the function 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;

Here is my code for display the chart above a table of data.

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

It work fine when there is only one function-openEvt(). But when I add in the setChart(), the tab wont function and no any data is display.

Yes, you can! You may add as many as you need, but be careful as it slows load time.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM