我知道会有一个简单的方法来完成这个,只是努力让我的头脑绕过它。所以我有一个父 div,它包含多个 div,如果单击父 div 之外的 div,则需要一个开放类归因于它们。将尝试通过 html 示例进行解释。
HTML
<div id="mediaPlayer">
<div class="playerViewer">
<div class="playerViewControls">
<img src="img/player-button-prev.png" class="playerPrev" alt="prev" />
<img src="img/player-button-next.png" class="playerNext" alt="next" />
</div>
<div class="playerAll playerView">
<img src="img/placeholder/player-image.jpg" alt="placeholder image" />
</div>
<div class="playerPhoto playerView">
<img src="img/placeholder/player-image.jpg" alt="placeholder image" />
</div>
<div class="playerVideo playerView">
<img src="img/placeholder/player-image.jpg" alt="placeholder image" />
</div>
<div class="playerMap playerView">
<img src="img/placeholder/player-image.jpg" alt="placeholder image" />
</div>
<div class="playerRelated playerView">
<img src="img/placeholder/player-image.jpg" alt="placeholder image" />
</div>
</div>
<div class="playerControl">
<div class="playerBtn playerAll">
<img src="img/player-button-all.jpg" alt="player button all" />
<p>(120) ALL<br />MEDIA</p>
</div>
<div class="playerBtn playerPhoto">
<img src="img/player-button-photo.jpg" alt="player button photo" />
<p>(40) PLACE<br />PHOTOS</p>
</div>
<div class="playerBtn playerVideo">
<img src="img/player-button-video.jpg" alt="player button video" />
<p>(40) PLACE<br />VIDEOS</p>
</div>
<div class="playerBtn playerMap">
<img src="img/player-button-map.jpg" alt="player button map" />
<p>LOCATION<br />MAP</p>
</div>
<div class="playerBtn playerRelated">
<img src="img/player-button-related.jpg" alt="player button related" />
<p>(40) RELATED<br />MEDIA</p>
</div>
</div>
</div>
因此,如果单击 .playerBtn.playerAll,我希望该 div 和它在 .playerViewer 中的相应 div(在本例中为 .playerAll.playerView)接收打开的类以及在内部打开该类的任何其他 div # mediaPlayer 以打开类。
最佳答案
这是一个可能会起作用的 jQuery 函数。复杂的 DOM 遍历的原因是考虑到单个页面上可能有多个玩家的情况。
$(function() {
$('.playerControl .playerBtn').click(function() {
var $playerViewer = $(this).parent('.playerControl').prev('.playerViewer'),
// Remove the first class called playerBtn
$relatedEle = $playerViewer.find('.'+$(this).attr('class').replace(/playerBtn\s/gi,''));
// Add class
$(this).add($relatedEle).addClass('open');
// Remove class from siblings in two separate containers
$(this).siblings().removeClass('open');
$relatedEle.siblings().removeClass('open');
});
});
请在此处查看概念验证 fiddle :http://jsfiddle.net/kYqcn/
关于javascript - jquery 添加/删除父 div 之外的多个元素的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23559515/