简体   繁体   中英

Passing parameter to function in Javascript

I want to call the following in my code somewhere.

scrollIntoViewElement(main-nav);

The following is the function:

// Element to scroll into view
scrollIntoViewElement(element) {
    document.getElementById('element').scrollIntoView();
}

The function should scroll the page into the view of the provided element id.

Is this correct? Or should it be...

// Element to scroll into view
scrollIntoViewElement(element) {
    document.getElementById("\'" + element + "\'").scrollIntoView();
}

The code scrollIntoViewElement(main-nav); means "Take the value of main , subtract the value of nav , and then call scrollIntoViewElement passing the result in as a parameter. If you want to pass in the string main-nav , you need quotes to tell the JavaScript parser you're using a literal string: scrollIntoViewElement("main-nav");

Within the function, you don't use quotes, because you want to use the value of the parameter, not the literal string "element" .

So:

scrollIntoViewElement("main-nav");

and

// Element to scroll into view
scrollIntoViewElement(element) {
    document.getElementById(element).scrollIntoView();
}

This assumes you have an element with id="main-nav" in your document. It'll throw an exception if you don't, because getElementById will return null .

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