简体   繁体   中英

Add .addEventListener to a function

I have this following .js function:

function basketHandler(basket)
{
                if (basket != null)
{
                                if(basket.Tickets.length > 0)
                                {
                                                console.log("Basket is not null and has tickets");
                                }
                                else
                                { 
                                                console.log("Basket is not null but has no tickets");
                                }
                }
                else
                {
                                console.log("Basket is null");
                }
}

and I have been told I need to add an event listener to it, underneath the function, for it to work and output the relevant console.logs. So after the functions I have tried the following with no joy...

basket.addEventListener("EVENTNAME", eventhandler)

basket.addEventListener("onload", basketHandler);

document.addEventListener("onload", basketHandler);

element.addEventListener("onload", basketHandler);

I am sure there is something fundamental I am missing, I can see the errors this code brings up in the console, but I don't know what they mean, so its difficult for me to fix it blindly... I don't have a great grasp of Javascript so I'm probably truing to run before I can walk, but either way, it's something I need to get working... any help greatly appreciated.

EDIT - In response to: @David Thomas: The errors I'm getting in the console are just Uncaught ReferenceError: basket is not defined depending on which variation I try.

EDIT - I am also linked to a .js library here: https://tickets.leicesterymca.co.uk/Iframe/esrojsapi.js if that helps.

I believe you mean addEventListener . You're confusing it with the IE-only attachEvent .

document.addEventListener("DOMContentLoaded", function() { 
    basketHandler(basket);
});

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