[英]add and remove class with jquery
如何在单击第一个元素时在第二个元素上添加类并在单击第二个元素时将其删除。
<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>
我绑定了这段代码但不能正常工作,在所有 div 中添加和删除类
$('.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');
});
});
您将需要一点 javascript 或使用库作为 jQuery,我不太清楚您的答案,所以我希望这可以帮助您。
function add_class() { document.getElementById('element2').setAttribute("class", "style_button new_style"); } function remove_class() { //document.getElementById('element1').removeAttribute("class"); document.getElementById('element2').setAttribute("class", "style_button"); }
.style_button { width: 64px; height: 32px; border-radius: 25px; color: blue; background-color: #f7e33e; } .new_style { background-color: red; color: yellow; }
<div> <input id="element1" type="button" class="style_button" onclick="add_class()" value="Add"> <input id="element2" type="button" class="style_button" onclick="remove_class()" value="Remove"> </div>
有关更多信息,您可以访问https://www.w3schools.com/jsref/met_element_setattribute.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.