简体   繁体   English

如何使onclick toggleClass互斥?

[英]How to make onclick toggleClass mutually exclusive?

I am trying to make my card selections mutually exclusive, this is the code I came up with (I am a beginner, and I am studying JS atm): http://jsfiddle.net/4XM9A/5/ 我正在尝试使卡选择互斥,这是我想到的代码(我是初学者,并且正在研究JS atm): http : //jsfiddle.net/4XM9A/5/

(function () {
    var links = Array.prototype.slice.call(document.querySelectorAll('.gacca1'));
    var links2 = Array.prototype.slice.call(document.querySelectorAll('.gacca2'));

    links.forEach(function (link) {
        link.addEventListener('click', function () {
            toggleClass('active', this);
        });
    });
    links2.forEach(function (link) {
        link.addEventListener('click', function () {
            toggleClass('active', this);
        });
    });
    function toggleClass(className, element) {
        element.classList.toggle(className);
    }
}());

As you can see, when you select card A, it shows the "card A text" on the right, when you select card B right after, it doesn't remove the ".active" class from card A. Thus both cards are active, and card B is always the one winning over. 如您所见,当选择卡片A时,它在右侧显示“卡片A文本”,而在之后选择卡片B时,它不会从卡片A中删除“ .active”类。因此,两个卡片都是活跃,并且卡B始终是获胜的一张。

I am trying to make so that if no cards are selected, it says - select a card. 我试图做出这样的选择:如果未选择任何卡,则说-选择一张卡。 If card A is selected - Card A block is shown on the right with relevant instructions. 如果选择了卡A-右侧将显示卡A块,并带有相关说明。 If card B is selected - Card B block is shown on the right with relevant instructions. 如果选择了卡B,则会在右侧显示卡B块并提供相关说明。 These card selections should be mutually exclusive, so toggling one should untoggle the other one. 这些卡选择应该是互斥的,因此切换一个应该取消切换另一个。

You've got the right idea. 您有正确的主意。 Basically, in your click handler function you need to make sure that the element that was clicked is the only one that gets the active class. 基本上,在单击处理程序函数中,需要确保被单击的元素是唯一获得active类的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM