當我單擊輪播中每個專案的按鈕時,我試圖切換顯示的文本。
當我使用“getElementByID”時,它作業正常,但我需要使用“getElementsByClassName”,因為它是后端的一個轉發器欄位,整個輪播中有幾個按鈕。
無論如何,這是我的代碼 -
function toggleText(){
var x = document.getElementsByClassName("figure-caption-test");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button class="figure-button" id="figure-button" onclick="toggleText()">
REVEAL ANSWER
</button>
<figcaption class="figure-caption-test" id="reveal-text" style="display: none;">
Text that appears
</figcaption>
我得到的錯誤是 - 無法讀取未定義的屬性(讀取“顯示”)
非常感謝任何幫助,謝謝
uj5u.com熱心網友回復:
getElementsByClassName回傳元素陣列。這是我的解決方案:
function toggleText(){
var elms = document.getElementsByClassName("figure-caption-test");
Array.from(elms).forEach((x) => {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
})
}
<button class="figure-button" id="figure-button" onclick="toggleText()">
REVEAL ANSWER
</button>
<figcaption class="figure-caption-test" id="reveal-text" style="display: none;">
Text that appears
</figcaption>
uj5u.com熱心網友回復:
我認為缺少 for 回圈和計數變數。
您的代碼應如下所示:
var x = document.getElementsByClassName("figure-caption-test");
var i;
for (i=0; i < x.length; i ) {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
uj5u.com熱心網友回復:
“getElementsByClassName”回傳一個類似陣列的物件,而不是單個物件。
您可以使用 forEach 迭代物件:
Array.prototype.forEach.call(x, function(element) {
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}
);
您可以在此處找到更多相關資訊:https : //developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/330680.html
標籤:javascript 按钮 不明确的 切换
