简体   繁体   English

如何<button>使用jQuery</button>使之<button>像单选按钮</button>

[英]How to make <button> act like a radio button with jQuery

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. 如果单击<button> ,则.active类将从先前选择的任何按钮中删除,并添加到我选择的任何按钮中。 Only one can be selected. 只能选择一个。

How can I do this with jQuery? 我该如何使用jQuery?

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: 每次用户单击其中的任何一个,都从所有按钮中删除active类,并将其添加到单击的按钮中:

$(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');
});

Try something like this: 尝试这样的事情:

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

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

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

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