为什么getElementById需要箭头功能?

时间:2018-12-20 07:57:38

标签: javascript getelementbyid

有人可以解释为什么buttonNames.map(button => document.getElementById(button))有效而不是buttonNames.map(document.getElementById)吗?

function testOK() {
    const buttonNames = ["b1", "b2", "b3", "b4"]

    const buttons = buttonNames.map(
        button => document.getElementById(button))

    buttons.forEach(button =>
        button.classList.add("red"))
}


function testNOK() {
    const buttonNames = ["b1", "b2", "b3", "b4"]

    buttons = buttonNames.map(document.getElementById)
    /* Firefox : TypeError: 'getElementById' called on an object that does not implement interface Document */
    /* Chrome : Uncaught TypeError: Illegal invocation */

    buttons.forEach(button =>
        button.classList.add("red"))
}
.red{
    background-color: red
}

button {
    display: block;
    margin-bottom: 10px;
}
<!DOCTYPE html>
    <html>
    <head>
        <title>test</title>
    
    </head>
    
    
    <body>
    <button onclick="javascript:testOK();">working</button>
    <button onclick="javascript:testNOK();">not working</button>
    
    <button id="b1">button 1</button>
    <button id="b2">button 2</button>
    <button id="b3">button 3</button>
    <button id="b4">button 4</button>
    </body>
    </html>

0 个答案:

没有答案