[英]each loop should only run once when button is clicked
我想在單擊按鈕時隱藏一個 div,然后顯示具有相同 class 的下一個 div。 我試過使用這段代碼,但是當我這樣做時,我想要顯示的下一個 div 也會淡出。
$('.arrow:last-of-type').on('click', function(){
$( ".collaboration" ).each(function( index ) {
if($('.collaboration').css('display') == 'block'){
$(this).fadeOut()
$(this).next().fadeIn()
}
})
})
有沒有辦法阻止 each() 在執行一次時停止運行,然后在單擊操作發生時再次運行?
這是 HTML:
<div id="collaborations">
<p class="arrow"><</p>
<div class="collaboration">
<img src="./img/test.png" />
<p>Text</p>
<a href="#" target="_blank"><button>Visit</button></a>
</div>
<div class="collaboration">
<img src="./img/test.png" />
<p>Text</p>
<a href="#" target="_blank"><button>Visit</button></a>
</div>
<div class="collaboration">
<img src="./img/test.png" />
<p>Text</p>
<a href="#" target="_blank"><button>Visit</button></a>
</div>
<p class="arrow">></p>
</div>
</div>
謝謝
你可以通過不遍歷.collaboration
來解決這個問題。
關鍵是您需要跟蹤當前顯示的是哪一個。 如果您知道這一點,那么您的點擊處理程序可以做的是顯示下一個並隱藏當前的。
我建議在與 .collaboration 相同的 div 上使用.collaboration
.active
然后,您可以通過$('.active').next().addClass('.active')
select 下一個 div,並通過$('.active').removeClass('.active')
('.active').removeClass('.active') 取消選擇。
您可能需要在 select 下一個元素之前存儲對第一個元素的引用
這是一個如何工作的簡單示例: https://codepen.io/juancaicedo/pen/LYGgPWa
我在 html 周圍移動,將所有協作單獨分組到一個 div 中。
您會發現您必須通過上述解決方案考慮其他一些行為。 例如,在我的示例中,有兩個項目出現在屏幕上的時刻,導致它們的容器 div 增長並隨后縮小。
由於這些原因,我不喜歡在 javascript 中處理演示文稿(即使用 jquery 的fadeIn
/ fadeOut
)。
如果您能找到一種僅使用 css 的方法,我認為這是更可取的。 這是一個使用 css 轉換的示例https://codepen.io/juancaicedo/pen/ZEQqzrR
jQuery
的each
方法可以隨時通過在回調中返回 false 來停止,因此您可以通過執行以下操作來修復您的代碼:
$('.arrow:last-of-type').on('click', function(){
$( ".collaboration" ).each(function( index ) {
if($('.collaboration').css('display') == 'block'){
$(this).fadeOut()
$(this).next().fadeIn()
return false;
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.