2017-03-23 75 views
1

它會將每個日誌的false打印到控制檯。單擊導航鏈接並取消按鈕時,切換工作正常。我看過this question,並嘗試了所有建議,但仍遇到同樣的問題。hasClass()始終返回false(jquery),即使在切換時也是如此

// add new photo toggle 
 
$('#click_new_photo a').click(function() { 
 
    console.log($(".content").hasClass('show-new-photo')); 
 
    $(".content").find(".new-photo").toggleClass('show-new-photo'); 
 
    console.log($(".content").hasClass('show-new-photo')); 
 
}); 
 

 
$("#cancel_add_new_photo").click(function() { 
 
    console.log($(".content").hasClass('show-new-photo')); 
 
    $(".new-photo").toggleClass("show-new-photo"); 
 
    console.log($(".content").hasClass('show-new-photo')); 
 
});
.new-photo { 
 
    width: 300px; 
 
    height: 200px; 
 
    border-radius: 5px; 
 
    background: #34609d; 
 
    box-shadow: 1px 1px #d6d6d6; 
 
    position: fixed; 
 
    top: 50%; 
 
    left: 50%; 
 
    transform: translate(-50%, -50%); 
 
    -ms-transform: translate(-50%, -50%); 
 
    z-index: 100; 
 
    transition: opacity 0.5s ease; 
 
    opacity: 0; 
 
} 
 

 
.show-new-photo { 
 
    opacity: 1; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 
    <nav> 
 
    <ul> 
 
     <li id="click_new_photo"><a href="#">New Photo</a></li> 
 
    </ul> 
 
    </nav> 
 
    <div class="content"> 
 
    <div class="new-photo"> 
 
     <button id="cancel_add_new_photo">Cancel</button> 
 
    </div> 
 
    ... 
 
    </div> 
 
    ... 
 
</body>

+0

在您的演示沒有課''秀 - 新photo''內容 – guradio

+0

也選擇‘內容’相當距離‘內容’明顯不同 – Pointy

回答

2

hasClass方法不適用於子節點。

您可以使用類似的東西

return $(".content").find('.show-new-photo').length > 0; 
1

嘗試

console.log($(".content").hasClass('show-new-photo')); 

我相信這應該通過添加類的工作 「」在您選擇

+0

感謝您的回覆!它仍然顯示全部虛假,即使有變化 – stumped

+0

我通常會嘗試使用id這樣的東西。我已經在我的測試結束,我相信它應該工作。您可以嘗試使用id屬性並將您的代碼切換到此處:console.log($(「#contentID」)。hasClass('show-new-photo')); –

2

我相信

$(".content").find(".new-photo").toggleClass('show-new-photo'); 

只有切換「新-照片」元素「顯示,新照片」類,而不是「內容」元素。

除非我失去了一些東西

console.log($("content").hasClass('show-new-photo')); 

會出來把同樣的事情,無論是之前還是之後

$(".content").find(".new-photo").toggleClass('show-new-photo'); 

,因爲該行代碼不會改變與否$(」。內容「)具有類」show-new-photo「或不是。

另外它應該是$(「。content」),而不是$(「content」)。

+0

無論如何,如果這種方式有缺陷,我可以測試'show-new-photo'是否在屏幕上? – stumped

+0

@stumped不完全確定你的意思。你想測試DOM中的任何元素是否具有類「show-new-photo」 –

相關問題