我正在为两个 html 页面使用一个 js 文件
这是我的 html 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- <link rel="stylesheet" href="../assets/css/style.css"> -->
<!-- bootstrap -->
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.min.css">
</head>
<body>
<div id="salestable">
<label for="Type">Today</label>
<input type="radio" id="day" name="months" value="Today" checked>
<label for="Type">Peroid</label>
<input type="radio" id="range-period" name="months" value="Peroid" onchange="getperiod()">
<input type="date" name="Date" id="startdate" >
<input type="date" name="Date" id="end-date" >
</div>
<script src="../db.js"></script>
</body>
</html>
默认情况下会选中今天
单选按钮
如果选中了今天单选按钮,我想将 onchange 事件列表添加到第一个输入日期id = startdate
这是我在db.js
中尝试的代码
if(document.getElementById('day').checked){
// get date element
const day = document.getElementById('startdate');
day.addEventListener("change", function() {
console.log('hi);
});
}
我也在 html 中的脚本标签内尝试过,但代码不起作用
另一个疑问是
如果我在 html 的 script
标记中添加事件监听器
像这样
<script>
const day = document.getElementById('startdate');
day.addEventListener("change", function() {
console.log('hi');
});
</script>
代码工作正常并记录为 hi
但是当我在 db.js 文件中添加相同的代码时,代码不起作用
哪位帮忙解决一下
最佳答案
在您的 db.js
文件中,您忘记了 console.log('hi);
中的 '
。您必须使用 console.log('hi');
我将您的代码作为内联脚本运行,并且它有效!
const day = document.getElementById('startdate');
day.addEventListener("change", function() {
console.log('hi');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- <link rel="stylesheet" href="../assets/css/style.css"> -->
<!-- bootstrap -->
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.min.css">
</head>
<body>
<div id="salestable">
<label for="Type">Today</label>
<input type="radio" id="day" name="months" value="Today" checked>
<label for="Type">Peroid</label>
<input type="radio" id="range-period" name="months" value="Peroid" onchange="getperiod()">
<input type="date" name="Date" id="startdate" >
<input type="date" name="Date" id="end-date" >
</div>
</body>
</html>
关于javascript - 检查 radio 并且 addeventlistener 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68243405/