Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jquery添加和删除类_Javascript_Jquery_Wordpress - Fatal编程技术网

Javascript 使用jquery添加和删除类

Javascript 使用jquery添加和删除类,javascript,jquery,wordpress,Javascript,Jquery,Wordpress,如何在单击第一个元素时在第二个元素上添加类,并在单击第二个元素时将其删除 <div> <input type="radio" class="element1"> <input type="radio" class="element2"> </div> <div> <input type="radio" class="element1"> <input type="radio" class="eleme

如何在单击第一个元素时在第二个元素上添加类,并在单击第二个元素时将其删除

<div>
  <input type="radio" class="element1">
  <input type="radio" class="element2">
</div>

<div>
  <input type="radio" class="element1">
  <input type="radio" class="element2">
</div>

<div>
  <input type="radio" class="element1">
  <input type="radio" class="element2">
</div>

您将需要一点javascript或使用一个库作为jQuery,我不清楚您的答案,所以我希望这可以帮助您

函数添加_类(){
document.getElementById('element2').setAttribute(“类”,“样式按钮新样式”);
}
函数remove_class(){
//document.getElementById('element1')。removeAttribute(“类”);
document.getElementById('element2').setAttribute(“类”,“样式按钮”);
}
.style\u按钮{
宽度:64px;
高度:32px;
边界半径:25px;
颜色:蓝色;
背景色:#f7e33e;
}
.新款{
背景色:红色;
颜色:黄色;
}


感谢您添加编码尝试。请看下面我的答案。您正在编写的代码逻辑有缺陷,其行为应该是正常的。通过说
$('.element2').addClass('active')
您正在告诉JQuery将
className
应用于具有
className
element2
的所有元素。我的回答显示了如何仅将
类名
应用于单击了
类名
元素1
的元素的
同级
。这不会解决问题。OP的问题是想知道如何更改具有className.element2的同级元素上的类。在当今的编程世界中,使用内联事件处理程序也是不受欢迎的,所以我也不建议这样做。
$('.element1').on('click',function(){
   $('.element2').addClass('active');

});
$('.element2').on('click',function(){
   $('.element2').removeClass('active');

});
//On DOM ready, add click event handlers to elements with className element1
//When element1 is clicked, it gets all siblings with className element2 and adds the className you want
//Adds event handler for click on elements with className element2 and removes the className
//This solution is done using JQuery
$(function(){
    $('.element1').on('click', function(){
        $(this).siblings('.element2').addClass('active');
    });

    $('.element2').on('click', function(){
        $(this).removeClass('active');
    });
});