[英]jQuery toggle not toggling
我有一個頁面,里面有一堆像這樣編碼的假下拉菜單(我無法真正更改 HTML):
<div class="select">
<div class="wrapper calcdropdown">
<a href="#" class="dd-openercalc">Select a calculator</a>
<a href="#" class="dd-opener pulldown-arrow"> </a>
</div>
<ul class="selectbox">
<li>Dropdown item 1</li>
<li>Dropdown item 2</li>
<li>Dropdown item 3</li>
<ul>
</div>
當我單擊 calcdropdown DIV 中的任一鏈接時,我需要切換相應的選擇框 UL。 當我使用 toggle() 時,選擇框 UL 在我第一次單擊鏈接時出現,但在我再次單擊鏈接時不會消失。
var $j = jQuery.noConflict();
$j(document).ready(function() {
// hide all the dropdowns by default
$j(".selectbox").hide();
$j('.calcdropdown a').live('click',function(e) {
// hide the dropdowns in case another one's open
$j(".selectbox").hide();
var self = $j(this);
// show the selectbox for this link
var thisSelectbox = $j(this).parents('.select').children('.selectbox').toggle();
e.preventDefault();
});
});
這也不起作用:
var $j = jQuery.noConflict();
$j(document).ready(function() {
$j(".selectbox").hide();
$j('.calcdropdown a').live('click',function(e) {
$j(".selectbox").hide();
var self = $j(this);
var thisSelectbox = $j(this).parents('.select').children('.selectbox');
if(thisSelectbox.is(':hidden')) {
thisSelectbox.show();
} else {
thisSelectbox.hide();
}
});
});
顯示后如何隱藏選擇框?
刪除$j(".selectbox").hide();
從點擊功能。
否則,您總是在點擊功能中執行此步驟:
編輯:(我沒有意識到您使用的元素不止一種)
要隱藏 all.selectbox,除了與單擊相關的選擇框,請使用 not():
var $j = jQuery.noConflict();
$j(document).ready(function() {
// hide all the dropdowns by default
$j(".selectbox").hide();
$j('.calcdropdown a').live('click',function(e) {
var target=$j(this).parents('.select').children('.selectbox');
$j('.selectbox').not(target.toggle()).hide();
e.preventDefault();
});
});
根據您對另一個答案的評論,您正在尋求以下解決方案:
這有點亂,但如果你改變$j(".selectbox").hide();
在你的第一個例子中$j(".selectbox").not($j(this).parents('.select').children('.selectbox')).hide();
,你應該得到你所追求的行為。
這隱藏了所有.selectbox
元素,除了對應於當前鏈接的元素。 然后,您對toggle()
的調用應該按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.