这是我的代码:
<form>
<fieldset>
<legend>Appearance</legend>
<p>
<label>Select Race:</label>
<select id="Race">
<option value="human">Human</option>
<option value="faela">Faela</option>
<option value="domovoi">Domovoi</option>
<option value="arcon">Arcon</option>
<option value="tsaaran">Tsaaran</option>
</select>
</p>
<p>
<label>Select Gender</label>
<select id="Gender">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
</p>
<p>
<label for="range">Select Age:</label>
<input type="range" min="10" max="80" id="slider" value="10" name="range"> <span id="output"></span>
</p>
</fieldset>
</form>
<script>
window.onload = function() {
//Range
var val = $('#slider').val();
output = $('#output');
output.html(val);
$('#slider').on('change', function() {
output.html(this.value);
});
$('#Race').change(function() {
if (this.value == "faela") {
$('#slider').prop({
'min': 10,
'max': 70
});
}
if (this.value == "human") {
$('#slider').prop({
'min': 10,
'max': 80
});
}
$('#slider').val(10);
output.html('10');
});
}
</script>
当javascript作为.js文件保持独立时,我的代码工作正常。但是,当它在HTML中使用脚本标记时,它不起作用。不输出滑块值的输出。我对此进行了研究,发现我应该添加window.onload = function() {}
但是,即使添加它之后它也没有输出滑块的值。
请告诉我如何解决这个问题。 谢谢,
答案 0 :(得分:2)
您应该在控制台中看到错误,指出无法识别符号$
。这是因为您的文档不包含jQuery脚本。将以下内容添加到标题中:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(function() {
let output = $('#output');
let slider = $('#slider');
output.html(slider.val());
slider.on('change', function() {
output.html(this.value);
});
$('#Race').on('change', function() {
let min, max;
switch (this.value) {
case 'faela': min, max = 10, 70;
case 'human': min, max = 10, 80;
}
slider.prop({ min, max });
slider.val(min);
output.html(min);
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<legend>Appearance</legend>
<p>
<label>Select Race:</label>
<select id="Race">
<option value="human">Human</option>
<option value="faela">Faela</option>
<option value="domovoi">Domovoi</option>
<option value="arcon">Arcon</option>
<option value="tsaaran">Tsaaran</option>
</select>
</p>
<p>
<label>Select Gender</label>
<select id="Gender">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
</p>
<p>
<label for="range">Select Age:</label>
<input type="range" min="10" max="80" id="slider" value="10" name="range"> <span id="output"></span>
</p>
</fieldset>
</form>
&#13;
答案 1 :(得分:0)
也许尝试使用DOMContentLoaded。
window.addEventListener('DOMContentLoaded', function () {
//code
}, false);