[英]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. 该功能应将页面滚动到提供的元素ID的视图中。
Is this correct? 这个对吗? Or should it be...
还是应该...
// Element to scroll into view
scrollIntoViewElement(element) {
document.getElementById("\'" + element + "\'").scrollIntoView();
}
The code scrollIntoViewElement(main-nav);
代码
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");
意思是“取
main
的值,减去nav
的值,然后调用scrollIntoViewElement
并将结果作为参数传递。如果要传递字符串main-nav
,则需要引号告诉您正在使用的JavaScript解析器文字字符串: 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"
. 在函数内,您不使用引号,因为您要使用参数的值,而不是文字字符串
"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. 假定您的文档中有一个
id="main-nav"
的元素。 It'll throw an exception if you don't, because getElementById
will return null
. 如果不这样做,它将引发异常,因为
getElementById
将返回null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.