Javascript 函数内部的变量getElementbyId

Javascript 函数内部的变量getElementbyId,javascript,html,css,Javascript,Html,Css,有一件事我不明白。我有一个函数,它接受dom元素的id作为参数: 比如说 HTML <ol id="ol"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ol> 初始化 whatever(ol) 为什么在函数中执行console.log(element)时,它会显示null?我遗漏了什么?无论

有一件事我不明白。我有一个函数,它接受dom元素的id作为参数:

比如说

HTML

<ol id="ol">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ol>
初始化

whatever(ol) 

为什么在函数中执行
console.log(element)
时,它会显示
null
?我遗漏了什么?

无论什么(“ol”)
都应该起作用。

我相信你的问题有两方面:

  • 你的视野有问题。变量
    元素
    which
    函数中定义和分配,这意味着您在该函数之外看不到它。您希望从函数返回调用document.getElementId的结果

    function whatever(id) {
        return document.getElementById(id);
    }
    
    var element = whatever("ol");
    
  • 必须将表示元素id的字符串传递给函数

    function whatever(id) {
        return document.getElementById(id);
    }
    
    var element = whatever("ol");
    

  • 有了这两样东西,
    元素
    现在将成为对正确HTML元素的引用。

    希望id作为字符串进行搜索。->
    whatever(“ol”)
    Try
    whatever(“ol”)
    @Lauromine我需要做一些通用的东西,不仅仅是为了“ol”,这就是为什么我要做一个函数。现在有三个人告诉你,你需要将元素标识符作为字符串传递…(除非
    ol
    定义为JS变量)。你想要实现什么?如果您只想拥有与
    getElementById
    功能相同的“自己的”函数,只需执行
    var whather=document.getElementById