繁体   English   中英

ID 不存在,虽然它存在

[英]ID doesn't exist although it does

我正在为 class 开发一个项目,并且我有一个 ID 为“idSelect”的下拉框。 但是当我尝试将下拉框的值抓取到一个变量中时,它说idSelect没有定义。

我尝试更改 id 的名称,但同样的事情发生了。 如果我尝试console.log(idSelect.value) ,它会显示为我选择的任何内容,但它仍然显示idSelect未定义的错误。

这是在头标签和脚本标签中

var selectedHero = idSelect.value;

这是在正文标签中

Change your avatar:
    <select id="idSelect">
        <option>Batman</option>
        <option>Spider-Man</option>
        <option>Iron Man</option>
        <option>Superman</option>
        <option>Wolverine</option>
    </select>

变量selectedHero应该存储玩家在 Dropbox 中选择的任何内容,例如“钢铁侠”或“超人”,但在 Inspect 元素中,它所说的只是:

Monster Project (BLANK).html:22 Uncaught ReferenceError: idSelect is
not defined
    at file:///C:/Users/chim%20chimoi/Desktop/Ifra/APCOMSCI/Monster_Project_HOME/Monster%20Project%20(BLANK).html:22:22

这以前有效,我没有改变任何东西,但是当我再次运行它时,这个错误刚刚开始弹出。

您将 HTML 的 id 传递给 Javascript,在 Javascript 中没有声明这样的变量 idSelect,例如:

var idSelect;

但是即使您在 Javascript 中声明它,将 HTML 的值传递给 Javascript 的方式也不正确。

如果你想保持相同的变量名,你可以这样做:

var idSelect = document.getElementById('idSelect').value;

您将需要使用getElementById ,因为 javascript 需要 go 在 DOM 中搜索 id:

 var selectedHero = document.getElementById("idSelect"); console.log(selectedHero.value) // Batman
 <select id="idSelect"> <option>Batman</option> <option>Spider-Man</option> <option>Iron Man</option> <option>Superman</option> <option>Wolverine</option> </select>

要让它更新,您还需要添加一个(更改)侦听器:

 var selectedHero = document.getElementById("idSelect"); selectedHero.addEventListener("change", ()=>{ console.log(selectedHero.value) // will console log the value whenever the select is changed });
 <select id="idSelect"> <option>Batman</option> <option>Spider-Man</option> <option>Iron Man</option> <option>Superman</option> <option>Wolverine</option> </select>

https://www.w3schools.com/jsref/met_document_getelementbyid.asp

很可能有一个变量“idSelect”不存在,或者在您引用它时无法访问。

尝试使其全球化:

<script>
    window.idSelect = document.getElementById('idSelect');
</script>

或每次需要时都像这样引用它:

<script>
    var idSelect = document.getElementById('idSelect');
    var selectedHero = idSelect.value;
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM