无法读取null的属性'value',就像那样简单但是甚至无法工作
window.onload = function(){
我该怎么做才是我的代码
window.onload = function(){
var shashank = document.getElementById('shashank').value;
var kiran = document.getElementById('kiran').value;
var sumanth = document.getElementById('sumanth').value;
var arun = document.getElementById('arun').value;
var arr = [shashank,kiran,sumanth,arun];
document.getElementById('btn').addEventListener('click', showName);
}
html是这样的:
<html>
<head>
<title>Attendance Sheet</title>
<script src="app.js"></script>
<style>
#present{
width:50px;
height:50px;
}
</style>
</head>
<body>
<select>
<option value="shashank">Shashank</option>
<option value="kiran">Kiran</option>
<option value="sumanth">Sumanth</option>
<option value="arun">Arun</option>
</select>
<button id="present">P</button>
<button id="btn">Submit</button>
</body>
</html>
答案 0 :(得分:0)
你必须更新你的html以包含这样的ID:
<option id="shashank" value="shashank">Shashank</option>
或者您可以获得以下选项:
let options = document.getElementsByTagName("option");
答案 1 :(得分:0)
这只是因为你试图获得没有id的元素,让我们来看看MDN official documentation for getElementByID 并查看CodePen
中的固定样本<option id="shashank" value="shashank">Shashank</option>
<option id="kiran" value="kiran">Kiran</option>
<option id="sumanth" value="sumanth">Sumanth</option>
<option id="arun" value="arun">Arun</option>
答案 2 :(得分:0)
除了您的<option>
标签没有您尝试访问的ID,我认为您尝试做的并不是最佳的。如果您有100个选项的选择会发生什么?我认为最好的方法是为您的选择创建eventListener
并仅获取所选选项。
window.onload = function(){
document.getElementById('btn').addEventListener('click', showName);
var myOpt = document.getElementById('mySelect').value; // myOpt = shashank
document.getElementById('mySelect').addEventListener('change', function(ev) {
// here you can save your selected option and do whatever you want
myOpt = ev.target.value
});
}
不要忘记在mySelect
代码中添加ID <select>
!
<html>
<head>
<title>Attendance Sheet</title>
<script src="app.js"></script>
<style>
#present{
width:50px;
height:50px;
}
</style>
</head>
<body>
<select id="mySelect">
<option id="shashank" value="shashank">Shashank</option>
<option id="kiran" value="kiran">Kiran</option>
<option id="sumanth" value="sumanth">Sumanth</option>
<option id="arun" value="arun">Arun</option>
</select>
<button id="present">P</button>
<button id="btn">Submit</button>
</body>
</html>