Подтвердить что ты не робот

ToggleClass и удалить класс из всех остальных элементов

Как я могу toggleClass и удалить класс из всех других элементов? Рассмотрим div, содержащий теги: HTML:

<div class="size">
   <a href="">blahblah</a>
   <a href="">blahblah</a>
</div>

JQuery

 $(".size a").click(function(){
 $(this).toggleClass('checked');
 if($(".size a").hasClass('checked')){
     $(this).removeClass('checked');
  }
 })

Я хочу добавить класс "cheched" в элемент и удалить класс "ckeched" из других элементов, у которых есть класс "checked". Мой код удаляет все классы. Как я могу добавить определенный класс и удалить другой класс элемента щелчком? Спасибо заранее

4b9b3361

Ответ 1

Это сделает это

 $(".size a").click(function(){
    $('.size a.checked').not(this).removeClass('checked');
    $(this).toggleClass('checked');
 })

Обновление

В качестве альтернативы вы могли бы сделать

 $(".size").on('click','a', function(){
    $(this).toggleClass('checked').siblings().removeClass('checked');
 })

Ответ 2

Только вам нужно использовать его.:)

<script>
    $(document).ready(function () {
        $('.demo_class').click(function () {
            $(this).toggleClass('active').siblings().removeClass('active');
        });
    });
</script>

Ответ 3

Так поздно, но мой ответ

$(".size").click(function(){ $('.size').removeClass('checked') //Clear all checked class on .size $(this).addClass('checked') //Add checked class to current clicked .size })

Его чище, мощно и безопасно.

Ответ 4

Я предполагаю, что у вас есть класс "размер", который содержит несколько элементов, из которых только один должен иметь возможность "проверять" класс в любой момент времени.

$(".size a").click(function()
{
    if($this).hasClass('checked')
    {
        $(".size a").removeClass('checked');
        $(this).addClass('checked');
    }
    else
    {
        $(this).removeClass('checked');
    }
}

Ответ 5

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>On click Change Css</title>
    <link rel="stylesheet" href="css/style.css" >
    <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
    <script>
        $(document).ready(function(){
            $('.main').click(function(){
                $(this).toggleClass('main1').siblings().removeClass('main1');;
             });
        });
    </script>

</head>

<body>

    <center>
        <div class="main" id="main-box">
            <h2>This is main Heading</h2>
            <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
            </p>
        </div>
        <div class="main">
            <h2>This is main Heading</h2>
            <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
            </p>
        </div>
        <div class="main">
            <h2>This is main Heading</h2>
            <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
            </p>
        </div>
    </center>

</body>

Css

.main {
  width:300px;
  margin:30px;
  margin:20px 25px;
  text-align:center;
  background-color:#CCC;
  padding:20px;
  display:inline-block;
}
.main:hover {
  cursor:pointer;
}
.main1 {
  width:300px;
  margin:30px;
  margin:20px 25px;
  text-align:center;
  background-color:#CCC;
  padding:20px;
  border:3px solid #036;
}

Ответ 6

$('.size a').on('click', function (e) {     
                    e.preventDefault();

                    $(this).removeClass("checked");
                    $(this).slideToggle();  
                 $(this).toggleClass('checked').removeClass('checked');

                });

Ответ 7

Исходный код jquery

$('button').click(function(){
  $('.toggle').toggleClass('red green');
});

Полный Предварительный Исходный код с Демо для toggleclass Add & Remove