我想知道是否有办法简化此代码。
基本上,#griffyindor在页面加载时默认具有'active'类。当它有“活跃”类时,我想要显示所有其他房屋(斯莱特林,拉文克劳和赫奇帕奇)。但是,在某些时候,当我点击其他内容时,它可能会失去“活跃”课程。但是当我点击回来时,我又想要初始行为。
有没有办法简化下面的内容,以检查gryffindor何时具有'主动'类或何时点击gryffindor(以便它获得'主动'类)?
$(function() {
var gryffindor = $('#gryffindor');
if (gryffindor.hasClass('active')) {
console.log('show all the houses');
$('#slytherin, #ravenclaw, #hufflepuff').show();
}
gryffindor.bind('click', function() {
if (gryffindor.hasClass('active')) {
console.log('all is active');
$('#slytherin, #ravenclaw, #hufflepuff').show();
}
});
});
答案 0 :(得分:0)
怎么样:
$(function() {
$('#gryffindor').on('click', function(e) {
this.toggleClass('active');
if (this.hasClass('active'); {
$('#slytherin, #ravenclaw, #hufflepuff').show();
} /*else {
$('#slytherin, #ravenclaw, #hufflepuff').hide();
}*/ //Not sure if this is part of what you want
}
});
答案 1 :(得分:0)
$(function() {
var $gryffindor = $('#gryffindor');
$('#slytherin, #ravenclaw, #hufflepuff').hide();
$gryffindor.on('click', function(e) {
$(this).toggleClass('active');
if ($(this).hasClass('active')) {
$('#slytherin, #ravenclaw, #hufflepuff').show();
} else {
$('#slytherin, #ravenclaw, #hufflepuff').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="gryffindor">Griffindor</button>
<div id="slytherin">slytherin</div>
<div id="ravenclaw">ravenclaw</div>
<div id="hufflepuff">hufflepuff</div>
答案 2 :(得分:0)
试试这个:
var houses = $("#houses li");
$(document).on('click', '#houses li', function(){
var activate_house = this;
$(houses).each(function (index) {
var house = this
$(house).removeClass('active');
$(house).removeClass('show');
});
$(activate_house).addClass('active');
showHouses();
});
function showHouses(){
$(houses).each(function (index) {
if(!$(this).hasClass('active')){
$(this).addClass('show');
}
});
}
showHouses();
&#13;
.show{
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul id="houses">
<li class="active" id="gryffindor">gryffindor</li>
<li id="slytherin">slytherin</li>
<li id="ravenclaw">ravenclaw</li>
<li id="hufflepuff">hufflepuff</li>
</ul>
&#13;
不缩小代码但简化阅读并添加语义,请参阅JSFIDDLE