首页 > 解决方案 > 将函数移到循环外

问题描述

我试图将函数置于循环之外,然后从内部调用它,但我不知道该怎么做。

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.

标签: javascriptfunctionfor-loopundefined

解决方案


你几乎明白了......问题是你正在调用函数并传递结果。相反,您只想传递函数本身,就像它是一个对象一样。尝试这个:

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,然后使用它的结果,这不是你想要的。


推荐阅读