未捕获的类型错误:无法设置 null Javascript 的属性“onchange”
2017-02-20
3312
尝试在 JS 中编写一个简单的均衡器,用户使用滑块控制 maxRadius,但我一直收到此错误
Uncaught TypeError: Cannot set property 'onchange' of null.
这是我的功能:
maxRadius 是声明的全局变量。
document.querySelector("#slider1").onchange = function(e) {
console.log("value=" + e.target.value);
document.querySelector("#sliderResults").innerHTML = e.target.value;
maxRadius = e.target.value * 500;
};
这是我的 html
<div>
<label for="slider1">Circle Size</label>
<input id="slider1" type="range" min="0.1" max="1.0" step="0.1" value="0.5" />
<span style="float:right" id="sliderResults"></span>
</div>
2个回答
尝试一下
document.getElementById("slider1").onchange = function(e)
{
console.log("value=" + e.target.value);
document.querySelector("#sliderResults").innerHTML = e.target.value;
maxRadius = e.target.value * 500;
};
Haze
2017-02-20
你只需确保文件已准备好
像这样尝试
function fn() {
document.querySelector("#slider1").onchange = function(e) {
console.log("value=" + e.target.value);
document.querySelector("#sliderResults").innerHTML = e.target.value;
maxRadius = e.target.value * 500;
};
}
document.onreadystatechange = function() {
if (document.readyState === 'complete') {
fn();
}
};
function fn() {
document.querySelector("#slider1").onchange = function(e) {
console.log("value=" + e.target.value);
document.querySelector("#sliderResults").innerHTML = e.target.value;
maxRadius = e.target.value * 500;
};
}
document.onreadystatechange = function() {
if (document.readyState === 'complete') {
fn();
}
};
<div>
<label for="slider1">Circle Size</label>
<input id="slider1" type="range" min="0.1" max="1.0" step="0.1" value="0.5" />
<span style="float:right" id="sliderResults"></span>
</div>
Anik Islam Abhi
2017-02-20