我仍然是脚本的新手,但我知道我想做的事情并非不可能。我试图使用一个选择选项来显示div,我现在有它,所以它目前一次显示1个div但我不能让它同时显示2个单独的div。所以例如我试图选择选项1,并取消隐藏所选的相同选项。 我尝试了" Can an Option in a Select tag carry multiple values?"
中的建议但没有一个工作
<script>
document
.getElementByValue('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementByValue(this.value);
if (vis !== null) {
vis.className = 'initial';
}
if (target !== null ) {
target.className = 'vis';
}
});
</script>
&#13;
<div class="header">
<select name="dropdown" id='target'>
<option value="temp1" value2="form1">option1</option>
<option value="temp2" value2="form2">option2</option>
</select>
</div>
<div class="temps">
<div id="temp1" class="initial"><?php include "temp1.php"; ?></div>
<div id="temp2" class="initial"><?php include "temp2.php"; ?></div>
</div>
<div class="forms">
<div id="form1" class="initial"><?php include "form1.php"; ?></div>
<div id="form2" class="initial"><?php include "form2.php"; ?></div>
</div>
&#13;
答案 0 :(得分:0)
您的选择器错误document.getElementById()
而不是document.getElementByValue
。您正在使用querySelectorAll()
匹配所有.vis
类元素,因此您需要使用{{进行迭代1}}。并使用forEach
vis.length>0
document.getElementById('target').addEventListener('change', function() {
var vis = document.querySelectorAll('.vis'),
target = document.getElementById(this.value);
if (vis.length > 0) {
vis.forEach(function(a) {
a.className = 'initial';
console.log(a.outerHTML)
})
}
if (target !== null) {
target.className = 'vis';
}
console.log(target.outerHTML)
});
答案 1 :(得分:0)
document.getElementById('target').addEventListener('change', function () {
let divs = document.querySelectorAll('.initial, .vis'); // grab all divs that have the class "initial" or "vis"
for (let i = 0; i < divs.length; i++) {
// loop over all divs
let div = divs[i];
if (div.classList.contains(this.value)) {
// the div's class list contains the value of the select box, e.g. "option-1" or "option-2"
div.classList.remove('initial');
div.classList.add('vis'); // make the div visible
} else {
div.classList.add('initial');
div.classList.remove('vis'); // otherwise make the divs invisible
}
}
});
&#13;
.initial {
display: none;
}
&#13;
<div class="header">
<select name="dropdown" id="target">
<option value="option-1">option1</option>
<option value="option-2">option2</option>
</select>
</div>
<div class="temps">
<div class="initial option-1">Temp 1</div>
<div class="initial option-2">Temp 2</div>
</div>
<div class="forms">
<div class="initial option-1">Form 1</div>
<div class="initial option-2">Form 2</div>
</div>
&#13;