javascript - 将函数移到循环外
问题描述
我试图将函数置于循环之外,然后从内部调用它,但我不知道该怎么做。
const links = document.querySelectorAll( 'a' );
for ( let i = 0; i < links.length; i++ ) {
links[i].addEventListener( 'click', ( event ) => {
const targetID = '#' === event.currentTarget.getAttribute( 'href' ) ? 'start' : event.currentTarget.getAttribute( 'href' );
...rest of the function...
} );
}
这是我迄今为止尝试过的:
const links = document.querySelectorAll( 'a' );
function smoothScrolling( event ) {
const targetID = '#' === event.currentTarget.getAttribute( 'href' ) ? 'start' : event.currentTarget.getAttribute( 'href' );
...rest of the function...
}
for ( let i = 0; i < links.length; i++ ) {
links[i].addEventListener( 'click', smoothScrolling( event ) );
}
我不知道为什么,但我收到以下错误:Uncaught TypeError: Cannot read property 'currentTarget' of undefined
.
解决方案
你几乎明白了......问题是你正在调用函数并传递结果。相反,您只想传递函数本身,就像它是一个对象一样。尝试这个:
const links = document.querySelectorAll( 'a' );
function smoothScrolling( event )
{
const targetID = '#' === event.currentTarget.getAttribute( 'href' ) ? 'start' :
event.currentTarget.getAttribute( 'href' );
...rest of the function...
}
for ( let i = 0; i < links.length; i++ )
{
links[i].addEventListener( 'click', smoothScrolling );
}
通过指定不带任何参数的函数,它将被传递而不是被调用。你这样做的方式是调用smoothScrolling,然后使用它的结果,这不是你想要的。
推荐阅读
- javascript - 用于自动完成功能的 RegEx
- jquery - 如何为 HTML5 SVG 路径的过滤器设置动画以实现发光/模糊/阴影效果?
- windows - 如何在 remoteapp 中发布我的文档文件夹
- python - 如何在 GridLayout 中添加新小部件而不调整旧小部件的大小?
- python - 使用坐标点生成热图
- rest - 如何编组 springframework.web.multipart.MultipartFile
- sql-server - SQL Server Management Studio v18 命令行参数登录
- firebase - 2 个不同的 Firestore 接口
- gensim - Gensim Word2Vec 缺少输入词的向量
- c++ - 带 SetRange 的 S3Client::GetObject 返回错误数据?