我得到以下問題,這讓我很生氣。我試圖通過點擊搜索按鈕來顯示/隱藏搜索表單來打開它,並再次關閉它。現在,打開表單正常工作,但再次點擊圖標時,表單不會關閉。我沒有使用jQuery show()和hide()函數,而更喜歡保持這種方式。jQuery沒有顯示/隱藏不同的ID搜索元素後點擊按鈕
我jQuery是:
$('span#search-button').click(function() {
$('span#search-button').prop('id', 'search-button--active');
$('#drawer-search-form').removeClass('hidden');
});
// broken bit, what it should do is effectively revert to the hidden state we changed in the previous code, but needless to say it won't.
$('span#search-button--active').click(function() {
$('span#search-button--active').prop('id', 'search-button');
$('#drawer-search-form').addClass('hidden');
});
這是相應的HTML:
<div class="drawer-heading">
<!-- the starting state of the search form is hidden -->
<div id="drawer-search-form" class="drawer-search-form-style hidden">
<!--<?php get_search_form(); ?>-->
</div>
<div class="drawer-search-button">
<a href="#search-open">
<!-- the button that opens and supposedly closes the search form -->
<span id="search-button" class="fa fa-search fa-border-circle fa-border-circle-fill fa-border-circle-float fa-border-circle-large" aria-hidden="true">
</span>
</a>
</div>
</div>
現在我曾嘗試在改變選擇到任何我能想到的。我也嘗試使用event.preventDefault();
來檢查是否有其他的東西搞亂了它,但無濟於事。我也嘗試使用attr
而不是prop
,並將代碼的整個結構改爲不同的東西。
我一直在漫遊SO的解決方案,但沒有建議在其他線程工作我的代碼,悲傷。
坦率地說,它不會像第二個jQuery塊中指定的那樣做。這讓我覺得這是一個選擇問題;但我真的想盡一切辦法來修復選擇器......幫助將非常非常感激。
總結: 我有一個按鈕,打開搜索表單。這工作。但是當試圖通過再次按下該按鈕嘗試關閉時,它確實不會而是再次隱藏該元素。
與您的按鈕該ID不存在開始,第二次點擊將不會在它被調用的時候被綁定 - 或者做[delagated綁定](http://api.jquery.com/on/#direct-and-委派事件)或做一個if,並檢查您的原始按鈕點擊id,並更改按鈕的作用,具體取決於它的編號 – Pete
你好皮特,感謝您的指針!我會深入介紹你鏈接的文檔,然後去看看!謝謝! – Extricate
添加了一個答案來解釋你可以用例子做的不同選項 – Pete