将函数移出循环

Move function outside the loop

我试图将函数放在循环外,然后从循环内调用它,但我不确定该怎么做。

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