如何使像jQuery的单选按钮一样

时间:2022-07-01 23:02:41

I have a list of buttons that are in a table, and I essentially want them to act like radio buttons. If <button> is clicked, the .active class gets removed from whatever button was previously selected, and gets added to whichever one I selected. Only one can be selected.

我有一个表格中的按钮列表,我基本上希望它们像单选按钮一样。如果单击

How can I do this with jQuery?

我怎么能用jQuery做到这一点?

2 个解决方案

#1


1  

Give a common class to every button. Every time user clicks to any of them, remove active class from all buttons and add it to the clicked one:

为每个按钮提供一个公共类。每次用户点击其中任何一个时,从所有按钮中删除活动类并将其添加到单击的按钮中:

$(document).on('click', '.radio-button', function() {
   //Remove active class from all buttons
   $('.radio-button').removeClass('active');
   //Add active class to the clicked button
   $(this).addClass('active');
});

#2


1  

Try something like this:

尝试这样的事情:

var allButtons = $('table button'); // use appropriate selector

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

#1


1  

Give a common class to every button. Every time user clicks to any of them, remove active class from all buttons and add it to the clicked one:

为每个按钮提供一个公共类。每次用户点击其中任何一个时,从所有按钮中删除活动类并将其添加到单击的按钮中:

$(document).on('click', '.radio-button', function() {
   //Remove active class from all buttons
   $('.radio-button').removeClass('active');
   //Add active class to the clicked button
   $(this).addClass('active');
});

#2


1  

Try something like this:

尝试这样的事情:

var allButtons = $('table button'); // use appropriate selector

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