我的 JS 函式的基本結構有效。但是,它只影響 HTML 結構中要顯示和隱藏的第一個 DIV。
CSS 類“map-content”具有none顯示屬性。幾個容器將接收此類,因此最初將被隱藏。所有 DIV 容器都有自己的值,這在我的代碼中更改顯示屬性時是必需的。
這是我的函式,它基本上可以作業,但只顯示和隱藏帶有“map-content”類的第一個容器(在 HTML 結構中)。
function validate_3() {
var x = document.getElementById("location_select");
var y = x.options[x.selectedIndex].value;
var a = document.querySelector(".map-content");
var b = a.getAttribute('value');
{
if (y == b) {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
}
.map-content {
display: none;
}
<select id="location_select" onchange="validate_3">
<option disabled selected>Select location...</option>
<option value="de_germany">Berlin: Germany</option>
<option value="fr_france">Paris: France</option>
<option value="it_italy">Rome: Italy</option>
</select>
<div class="map-content" value="de_germany">
<h3>This is Berlin</h3>
<p>Berlin is in Germany</p>
</div>
<div class="map-content" value="fr_france">
<h3>This is Paris</h3>
<p>Paris is in France</p>
</div>
<div class="map-content" value="it_italy">
<h3>This is Rome</h3>
<p>Rome is in Italy</p>
</div>
注意代碼片段:我不知道為什么,但與我的測驗界面不同,這里沒有任何選擇。甚至不是正文中描述的結構中的第一個。
如果有更好的結構,我很高興得到一般性建議。
uj5u.com熱心網友回復:
你在這里缺少一組括號onchange="validate_3">,像這樣添加一組括號onchange="validate_3()">,你的第一個選擇應該可以作業
要獲得所需的內容,請確保已添加括號,如上所示。
javascript,
// take this line out of your funtion and change `querySelector` to
//`querySelectorAll`
var a = document.querySelectorAll(".map-content");
function validate_3() {
var x = document.getElementById("location_select");
var y = x.options[x.selectedIndex].value;
//use The forEach() method to executes a provided function once for each
//element.
a.forEach((element) => {
if (y != element.getAttribute("value")) {
(element.classList.add("map-content"))
} else {
element.classList.remove("map-content")
};
});
};
但實際上,最好不要使用 onclick 并通過 Javascript 代碼將事件處理程式附加到 DOM 節點。這被稱為不顯眼的 javascript。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/457695.html
標籤:javascript html css 功能 if 语句
上一篇:Angular-使用復選框在Leaflet地圖上顯示/洗掉圖層
下一篇:將重復的if陳述句轉換為回圈
