I am a Javascript beginner, I am trying to get some simple code working. I added one snippet as a check to make sure Javascript is working in the page, which it does. It just changes a bit of text from blue to red.
The second piece of code is supposed to hide a <div>
, or show it depending on the selected value. It does not work can somebody point me in the right direction? Thanks for any advice.
<!DOCTYPE html>
<html>
<head>
<title>getElementById example</title>
<script>
function changeColor(newColor) {
var elem = document.getElementById("para1");
elem.style.color = newColor;
}
</script>
<script>
// EXPAND
function Hide(elementid){
document.getElementById(elementid).style.display = 'none';
}
function Show(elementid){
document.getElementById(elementid).style.display = '';
}
</script>
</head>
<body>
<p id="para1">Some text here</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
<div id="one">ONE</div>
<div id="two">TWO</div>
<select>
<Option value="javascript:Show('one');javascript:Hide('two')">one</option>
<Option value="javascript:Hide('one');javascript:Show('two')">two</option>
</select>
</body>
</html>
The value
attribute does not run JavaScript.
You need to bind a change
event to the select element, and then look at the selected value to determine which one to show or hide.
<div id="one">ONE</div>
<div id="two">TWO</div>
<div id="three">THREE</div>
<select>
<option>one
<option>two
<option>three
</select>
<script>
function show(id) {
document.getElementById(id).style.display = '';
}
function hide(id) {
document.getElementById(id).style.display = 'none';
}
function whichDiv(event) {
var select = event.target;
var options = select.options;
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.selected) {
show(option.value);
} else {
hide(option.value);
}
}
}
document.querySelector('select').addEventListener('change', whichDiv);
</script>
我认为您应该使用block
: document.getElementById(elementid).style.display = 'block';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.