我在一个文件中处理Javascript/HTML/Jinja代码,现在我想把它拆分成单独的文件。
我的JS代码在拆分之前就可以工作了,但当我把它移到一个新文件时,注释掉的部分就停止了工作。我是自学成才的,所以这可能是显而易见的,但我还没有找到正确的信息。我无法访问元素,也不知道为什么。我该怎么修?还有:有没有地方讨论过为什么它在同一个文件中工作,但分开代码会这样破坏它?感谢您的真知灼见!
在移动之前,我的JS代码位于HTML的底部,我已经看到这有时会有所不同。我试过了
<script src>
在底部,但没有区别。
我的相关HTML(呈现的Jinja)代码块:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="keywords" content="download,bookshelf">
<meta name="description" content="UI with options to download Goodreads Bookshelf"/>
<link rel="stylesheet" href="/static/style.css" >
<link rel="stylesheet" href="/static/download_page.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">;</script>
<script src="/static/download_page.js"></script>
<title> Download Page | Group Bookshelf Tools</title>
</head>
<body class="color-scheme-dark">
<form action="/download_shelf/" method="post" name="choice_form">
<input id="csrf_token" name="csrf_token" type="hidden" value="...">
<form-title>
<label class="form-title" for="form_name">Download Form Options</label>
</form-title>
<form-row>
<label class="item-label" for="shelf_choice">Shelf Choice</label>
<select class="drop-down-menu" id="shelf_choice" name="shelf_choice" onchange="setShelfChoice()" required><option value="Generic Test Shelf">Generic Test Shelf</option><option value="Shelf One">Shelf One</option><option value="Shelf Two">Shelf Two</option></select>
</form-row>
<form-submit>
<input class="btn form-submit" id="submit" name="submit" type="submit" value="Submit">
</form-submit>
</form>
</div>
</body>
</html>
尝试过没有
this
但没有变化。
我的JS代码:
document.addEventListener('DOMContentLoaded', setShelfChoice());
function setShelfChoice() {
let el = document.getElementsByName('shelf_choice');
console.log("el type: ", typeof(el), el);
console.log("el value: ", el[0].value);
}
当我重新加载HTML页面时,它会调用函数,数组中有一个节点0,它具有所有正确的值。但如果不是[0],我不确定该打什么电话。
我试着改变
console.log("el: ", el[0].value);
到
console.log("el: ", el[0]);
输出只是说未定义。
我尝试添加一个初始化,但没有影响任何内容:
function setShelfChoice() {
let el = document.getElementsByName('shelf_choice');
if (el.selectedIndex == undefined) {
el.selectedIndex = 0;
}
console.log("el: ", typeof(el), el);
console.log("el: ", el.value);