我正在嘗試撰寫一個簡單的函式來動態顯示或隱藏元素。我以前寫過幾次這樣的函式,從來沒有遇到過問題……我不知道這里出了什么問題。我使用 Javascript 動態創建元素,然后在創建它并將其附加到頁面的程序中,我還撰寫$(element).css("display", "none")了它將在頁面加載時隱藏。
現在我正在撰寫一個事件偵聽器函式來顯示隱藏元素以回應單擊事件。當我單擊附加了此事件偵聽器的按鈕時,隱藏的元素會出現(太棒了!),但是當我再次單擊該框時,它們會留在頁面上。當我console.log退出該函式時,我可以看到它總是達到show條件而從未達到hide條件......但是在花費數小時查看示例并嘗試不同的實作之后,我無法弄清楚為什么。
需要明確的是,我沒有display: none;在靜態 CSS 樣式表中指定。我在創建元素時在 JS 中動態添加了它。
// Pass in an array of cards called "filterCards"
const toggleDisplayFilterCards = (filterCards) => {
// Loop through the cards, and for each card, grab the ID tag
for (let card of filterCards) {
card = `#filter-card-container_${card.id}`;
// If "display" style attribute = "none", show the div, else, hide it.
if ($(card).css("display", "none")) {
$(card).css("display", "")
console.log("show");
} else if ($(card).css("display", "")) {
$(card).css("display", "none");
console.log("hide");
}
}
};
有沒有人看到這個代碼永遠不會達到“隱藏”條件的原因?一旦元素顯示在頁面上,我已經檢查了控制臺中的元素,并確認 style 屬性已更改為"",所以當我單擊同一個按鈕時,我希望該功能能夠達到“隱藏”條件。
uj5u.com熱心網友回復:
這兩個做什么
$(card).css("display", "none")
$(card).css("display", "")
是他們設定卡片的樣式,然后回傳包含卡片的 jQuery 物件。物件在 JavaScript 中總是真實的,所以這樣做
if ($(card).css("display", "none")) {
沒有意義。
您需要檢索樣式(使用單個引數完成),然后將其與可能的值進行比較。
if ($(card).css("display") === "none") {
...
} else {
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411142.html
標籤:
