2013-11-21 83 views
0

我是Jquery的新手,在選擇時遇到了一些麻煩。我正在創建一種手風琴風格,並希望將活動的打開元素的框更改爲紅色。但是,當我將鼠標移開並打開另一部分時,我希望先前的紅色被刪除。但是我這樣做很麻煩。在Jquery中選擇問題

這裏是我的代碼:

CSS

body { 
    width: 500px; 
    margin: auto; 
    text-align: center; 
} 
dl { 
    width:500px; 
} 
dd { 
    margin: 0; 
    width:500px; 
    padding: 1em 0; 
    float:left; 
} 
dt { 
    cursor: pointer; 
    float:left; 
    width:500px; 
    line-height: 2em; 
    background: #e3e3e3; 
    border-bottom: 1px solid #c5c5c5; 
    border-top: 1px solid white; 
} 
dt:first-child { 
    border-top: none; 
} 
dt:nth-last-child(2) { 
border-bottom: none; 
} 
dt h1 { 
    float:left; 
    font-weight: bold; 
    font-size : 1.5em; 
    margin:0; 
    width:400px; 
} 
.box { 
    float:right; 
    background-color:#999999; 
    height: 30px; 
    width: 30px; 
} 
.bck { 
    background-color:#FF0000; 
} 
.hide { 
    display: none; 
} 

HTML 
<body> 
<dl> 
    <dt><h1>What are your hours?</h1><div class ="box">-</div></dt> 
    <dd>We are open 24/7.</dd> 
    <dt><h1>What are your hours?</h1><div class ="box">-</div></dt> 
    <dd>We are open 24/7.</dd> 
    <dt><h1>What are your hours?</h1><div class ="box">-</div></dt> 
    <dd>We are open 24/7.</dd> 
<dt><h1>What are your hours?</h1><div class ="box">-</div></dt> 
    <dd>We are open 24/7.</dd> 
    <dt><h1>What are your hours?</h1><div class ="box">-</div></dt> 
    <dd>We are open 24/7.</dd> 

</dl> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 

<script> 
(function() { 
var dd = $('dd'); 
dd.filter(':nth-child(n+4)').addClass('hide'); 
$('dt').on('mouseenter',function() { 
$(this).find("div").addClass('bck'); 
$(this).next().siblings('dd').hide(); 
$(this).next().siblings('dd').find("div").removeClass('bck'); 
$(this).next().show(); 

}) 

})(); 
</script> 




</body> 

回答

1

divdt元素不dd元素,所以你需要使用siblings('dt')siblings('dd')

jQuery(function ($) { 
    var $dd = $('dd'); 
    $dd.filter(':nth-child(n+4)').addClass('hide'); 
    $('dt').on('mouseenter', function() { 
     $(this).find("div").addClass('bck'); 
     $dd.hide(); 
     $(this).siblings('dt').not(this).find("div").removeClass('bck'); 
     $(this).next().show(); 
    }) 
}); 

演示:Fiddle

+0

爲什麼$ dd.hide()足以隱藏元素而不是$(this).next()。siblings('dd')。hide(); –

+0

@JacklynN因爲'$ dd'是一個引用所有'dd'元素的變量 –

0

你可以改變順序,首先從所有擁有它的元素中刪除'bck'類,並隱藏所有的dd。

$('dt').on('mouseenter',function() { 
    $('.bck').removeClass('bck'); 
    $('dd').hide(); 
    $(this).find("div").addClass('bck'); 
    $(this).next().show(); 
})