jQuery 如果选择了单选按钮 Show Div - 8 Radio Buttons / 8 Divs - 这可以简化吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18655710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:09:29  来源:igfitidea点击:

If Radio Button is Selected Show Div - 8 Radio Buttons / 8 Divs - Can this be simplified?

javascriptjqueryhtmlbuttonradio

提问by 50dollanote

Basically, I want 8 radio buttons. And if one radio button is selected then a div is shown below. If another button is selected another div is shown. Only one div shown at a time and if no button selected (initially) then no divs shown.

基本上,我想要 8 个单选按钮。如果选择了一个单选按钮,则下面会显示一个 div。如果选择了另一个按钮,则会显示另一个 div。一次只显示一个 div,如果没有选择按钮(最初),则不显示 div。

This is my HTML which is fairly standard, I'm not trying to improve this for what I need.

这是我的 HTML 相当标准,我并不想根据我的需要改进它。

<form id='group'>
    <label><input type="radio" name="group1" class="sim-micro-btn"/></label>
    <label><input type="radio" name="group1" class="sim-mini-btn"/></label> 
    <label><input type="radio" name="group1" class="sim-maxi-btn"/></label>
    <label><input type="radio" name="group1" class="sim-mega-btn"/></label>
    <label><input type="radio" name="group1" class="phone-smart-micro-btn"/></label>
    <label><input type="radio" name="group1" class="phone-smart-mini-btn"/></label>
    <label><input type="radio" name="group1" class="phone-smart-btn"/></label>
    <label><input type="radio" name="group1" class="phone-smart-maxi-btn"/></label>
</form>

<div class="billpay-internet-add-ons">
    <div class="sim-micro-desktop">sim-micro</div>
    <div class="sim-mini-desktop">sim-mini</div>
    <div class="sim-maxi-desktop">sim-maxi</div>
    <div class="sim-mega-desktop">sim-mega</div>
    <div class="phone-smart-micro-desktop">phone-smart-micro</div>
    <div class="phone-smart-mini-desktop">phone-smart-mini</div>
    <div class="phone-smart-desktop">phone-smart</div>
    <div class="phone-smart-maxi-desktop">phone-smart-maxi</div>
</div>

However this is my script and it seems fairly hectic and I'm wondering before I move on is there a way to do this a bit more simple?

然而,这是我的脚本,看起来相当忙碌,在我继续之前我想知道有没有办法更简单地做到这一点?

$(document).ready(function(){
    $('.sim-micro-desktop').hide();
    $('.sim-mini-desktop').hide();
    $('.sim-maxi-desktop').hide();
    $('.sim-mega-desktop').hide();
    $('.phone-smart-micro-desktop').hide();
    $('.phone-smart-mini-desktop').hide();
    $('.phone-smart-desktop').hide();
    $('.phone-smart-maxi-desktop').hide();


    $('form#group').click(function(){
        if($('.sim-micro-btn').is(":checked")){
            $('.sim-micro-desktop').show();
        } else {
            $('.sim-micro-desktop').hide();
        }     

        if($('.sim-mini-btn').is(":checked")){
            $('.sim-mini-desktop').show();
        } else {
            $('.sim-mini-desktop').hide();
        }     

        if($('.sim-maxi-btn').is(":checked")){
            $('.sim-maxi-desktop').show();
        } else {
            $('.sim-maxi-desktop').hide();
        }  

        if($('.sim-mega-btn').is(":checked")){
            $('.sim-mega-desktop').show();
        } else {
            $('.sim-mega-desktop').hide();
        }  

        if($('.phone-smart-micro-btn').is(":checked")){
            $('.phone-smart-micro-desktop').show();
        } else {
            $('.phone-smart-micro-desktop').hide();
        }  

        if($('.phone-smart-mini-btn').is(":checked")){
            $('.phone-smart-mini-desktop').show();
        } else {
            $('.phone-smart-mini-desktop').hide();
        }  

        if($('.phone-smart-btn').is(":checked")){
            $('.phone-smart-desktop').show();
        } else {
            $('.phone-smart-desktop').hide();
        }  

        if($('.phone-smart-maxi-btn').is(":checked")){
            $('.phone-smart-maxi-desktop').show();
        } else {
            $('.phone-smart-maxi-desktop').hide();
        }  

          });


});

回答by Rory McCrossan

Firstly put shared classes on both the radiobuttons and the divelements which show the content. In my example I've used triggerand contentrespectively. Then add a dataattribute to the radio to identify which div should be shown on click.

首先在radio按钮和div显示内容的元素上放置共享类。在我的例子中,我分别使用了triggercontent。然后data向收音机添加一个属性,以标识应在单击时显示哪个 div。

Shortened example:

缩短示例:

<form id='group'>
    <label>
        <input type="radio" name="group1" class="sim-micro-btn trigger" data-rel="sim-micro-desktop" />
    </label>
</form>
<div class="billpay-internet-add-ons">
    <div class="sim-micro-desktop content">sim-micro</div>
</div>

Then you only need 1 click handler like this:

那么您只需要 1 个单击处理程序,如下所示:

$(document).ready(function(){
    $('.trigger').click(function() {
        $('.content').hide();
        $('.' + $(this).data('rel')).show();
    });
});

You can also then use CSS to hide the divelements without jQuery - styling should always be done in CSS anyway as it's a much better separation of concerns.

然后,您还可以使用 CSS 来隐藏div没有 jQuery的元素 - 无论如何,样式应该始终在 CSS 中完成,因为它可以更好地分离关注点。

.content {
    display: none;
}

Example fiddle

示例小提琴

回答by billyonecan

You can hide the divelements using CSS:

您可以div使用 CSS隐藏元素:

.billpay-internet-add-ons div {
  display: none;
}

Then you can use the classNameof the targetto determine which divto show, hiding all siblingelements:

然后你可以使用classNametarget,以确定哪些div显示,隐藏所有sibling元素:

$('form#group').click(function(e) {
    var className = e.target.className.replace('btn', 'desktop');    
    $('.' + className).show().siblings().hide();
});

Here's a fiddle

这是一把小提琴

回答by billyonecan

var $billpay= $('.billpay-internet-add-ons');
$billpay.find("div").hide();
$("#group input:radio").click(function(){
  $billpay.find("div").hide();
  $billpay.find("div:eq("+$(this).parent().index()+")").show();    
}); 

http://jsfiddle.net/KaF77/2/

http://jsfiddle.net/KaF77/2/

回答by Oskar Hane

I simplified it some four you. Basically you look which index the radio clicked has and then show a div with the same index. So the position of the divs has to match the radios.

我把它简化了一些。基本上,您会查看无线电单击的索引,然后显示具有相同索引的 div。所以 div 的位置必须与收音机相匹配。

Your HTML is the same as before.

您的 HTML 与以前相同。

Your CSS:

你的 CSS:

.billpay-internet-add-ons > div {
    display:none;
}

All your Javascript:

你所有的Javascript:

$(document).ready(function(){
    $('form#group').click(function(e)
    {
        $('.billpay-internet-add-ons > div').hide();
        $('form#group input[type="radio"]').each(function(index)
        {
            if($(this).is(':checked'))
            {
                $('.billpay-internet-add-ons > div:eq(' + index + ')').show();
            }
        });
    });
});

jsFiddle Demo: http://jsfiddle.net/cfSXY/

jsFiddle 演示:http: //jsfiddle.net/cfSXY/

回答by Fenton

You could use selectors to reduce the number of lines of code here.

您可以使用选择器来减少此处的代码行数。

$('.sim-micro-desktop').hide();
$('.sim-mini-desktop').hide();
$('.sim-maxi-desktop').hide();
$('.sim-mega-desktop').hide();
$('.phone-smart-micro-desktop').hide();
$('.phone-smart-mini-desktop').hide();
$('.phone-smart-desktop').hide();
$('.phone-smart-maxi-desktop').hide();

Could be shortened to:

可以简写为:

$('.billpay-internet-add-ons div').hide();

This uses the parent element to group those elements you want to hide, rather than repeating the request for each one.

这使用父元素对要隐藏的元素进行分组,而不是对每个元素重复请求。

Similarly, you can use your naming convention to map the items to the elements to show and hide - here is the full working example:

同样,您可以使用命名约定将项目映射到要显示和隐藏的元素 - 这是完整的工作示例:

$(document).ready(function(){
    $('.billpay-internet-add-ons div').hide();

    $('form#group').click(function(){
        $('#group input').each(function() {
            var item = $(this);
            var isChecked = item.is(':checked');
            var name = item.attr('class').replace("-btn", "-desktop");

            if (isChecked) {
                $('.' + name).show();
            } else {
                $('.' + name).hide();
            }
        });
    });
});

This example is purely based on your HTML without any changes. See it working here.

此示例纯粹基于您的 HTML,没有任何更改。看到它在这里工作

You could simplify this further if you didn't need to transform the names. You could use a data-attribute instead of changing the class names to do this.

如果您不需要转换名称,则可以进一步简化此操作。您可以使用数据属性而不是更改类名来执行此操作。

回答by bipen

use html5 data attribute)(i.e data-mappingclass ) pointing to corresponding div you need to show. add same class to all radio button(ie radioClass).

使用 html5 数据属性)(即 data-mappingclass )指向您需要显示的相应 div。将相同的类添加到所有单选按钮(即 radioClass)。

HTML

HTML

 <label><input type="radio" name="group1" class="radioClass sim-micro-btn" data-mappingclass="sim-micro-desktop"/></label>
 <label><input type="radio" name="group1" class="radioClass sim-mini-btn" data-mappingclass="sim-mini-desktop"/></label>
 ... //same for others

JS

JS

$('.radioClass').click(function() {
  $('.billpay-internet-add-ons div').hide();
  if(this.checked){
     $('.' + $(this).data('mappingclass').show();
  }
});

回答by JohnMark13

You can firstly have everything hidden by default (except one form maybe) using CSS, which gets rid of this:

您可以首先使用 CSS 默认隐藏所有内容(可能除了一种形式),它摆脱了这个:

$('.sim-micro-desktop').hide();
$('.sim-mini-desktop').hide();
$('.sim-maxi-desktop').hide();
$('.sim-mega-desktop').hide();
$('.phone-smart-micro-desktop').hide();
$('.phone-smart-mini-desktop').hide();
$('.phone-smart-desktop').hide();
$('.phone-smart-maxi-desktop').hide();

This has a negative implication for users without javascript, if you're worried - they'll never be able to see the other forms.

如果您担心,这对没有 javascript 的用户有负面影响 - 他们将永远无法看到其他表单。

Next, only one radio can be checked, so just find out which one it is using:

接下来,只能检查一台收音机,因此只需找出它正在使用的收音机:

$('input[name=group1]:checked);

But why would you do that, so you have the radios have a click handler more like:

但是你为什么要这样做,所以你的收音机有一个更像的点击处理程序:

$('#group input[type="radio"').click(function(){
    //code to show/hide form
});

Now you have a choice as to how you link your radio buttons to the different forms one way could be to use the data attribute, so you define your radios like so:

现在您可以选择如何将单选按钮链接到不同的表单,一种方法是使用 data 属性,因此您可以像这样定义单选按钮:

<label><input type="radio" name="group1" class="phone-smart-maxi-btn" data-form="phone-smart-maxi-desktop"/></label>

Which you can access like so:

您可以像这样访问:

$('input[name=group1]:checked).data("form");

Now all you need to do is hide the div that was already showing, but that can be achieved with a similar use of the data attribute or by using the :visibleselector.

现在您需要做的就是隐藏已经显示的 div,但这可以通过类似使用 data 属性或使用:visible选择器来实现。