简体   繁体   English

如何在单独的 js 文件中使用 document.getElementById()?

[英]How do I use document.getElementById() in a separate js file?

Learning how to do webdev for the first time, and to make things neater, I'm storing my scripts in their own files.第一次学习如何做 webdev,为了让事情更整洁,我将我的脚本存储在他们自己的文件中。 I've been trying to figure out how to access elements from this separate file but I cannot figure out how.我一直在试图弄清楚如何从这个单独的文件中访问元素,但我不知道如何。

This is the relevant bit of the JS file这是JS文件的相关位

function getSelectedText() {
        if document.getElementById("card1").checked == true {
            //code here
        }
}

This is the relevant HTML it's trying to access这是它试图访问的相关 HTML

<script type="text/javascript" src="js/cards.js"></script>
<input id="card1" type="radio" name="card" value="1" checked>Test1<br>
<input id="card2" type="radio" name="card" value="2">Test2<br>
<input id="card3" type="radio" name="card" value="3">Test3<br>
<button onclick="updateCard()">View card</button>

I want to access and edit the radio inputs but the JavaScript file throws an error when I try to reference document.我想访问和编辑无线电输入,但是当我尝试参考文档时,JavaScript 文件会引发错误。 Is there any way to reference the HTML file or do I need to use a different method/shove the code into the html?有什么方法可以引用 HTML 文件,还是我需要使用不同的方法/将代码推入 html?

Firstly, it should be:首先,它应该是:

if (document.getElementById("card1").checked)

You forgot the pair of bracket.你忘记了那对支架。 As for getting the JavaScript code to work, you'll need a <script src="your js file"></script> element in your HTML file, and the code should work just all right.至于让 JavaScript 代码工作,您需要在 HTML 文件中添加一个<script src="your js file"></script>元素,并且代码应该可以正常工作。

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

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