如何使用Jquery基于单选按钮显示<div>内容

时间:2018-01-11 01:03:39

标签: jquery asp.net-mvc

我想根据<div class="Add1">选项显示<div class="delivery">内容。请帮我。提前谢谢。

我的代码:

<div class="delivery">
    <label>
        <input type="radio" name="DeliveryChoice" value="false" checked />
        <span>Deliver my order to me</span>
    </label>
    <label>
        <input type="radio" name="DeliveryChoice" value="true"  />
        <span>I will pick up my order</span>
    </label>
    <label>
        <input type="radio" name="DeliveryChoice" value="true" />
        <span>I will pick</span>
    </label>
</div>

<div class="Add1">
 <div>Order address</div>

  <div>Order </div>

   <div>Order me</div>

</div>

JQuery是:

var address = $('.Add1');
$('.delivery input[type="radio"]').change(function() {
    console.log($(this).val());
     if ($(this).val() === 'false') {
        address.hide();
    }
   else if ($(this).val() === 'true') {
        address.show();
    } else {
        address.show();
    }
});

1 个答案:

答案 0 :(得分:1)

首先提供<div>属性

中的每个id元素
<div class="Add1">
    <div id="A">Order address</div>
    <div id="B">Order</div>
    <div id="C">Order me</div>
</div>

并在与适当的data匹配的单选按钮中添加id属性。

<div class="delivery">
    <label>
        <input type="radio" name="DeliveryChoice" value="false" data-divid="A" checked />
        <span>Deliver my order to me</span>
    </label>
    <label>
        <input type="radio" name="DeliveryChoice" value="true" data-divid="B" />
        <span>I will pick up my order</span>
    </label>
    <label>
        <input type="radio" name="DeliveryChoice" value="true" data-divid="C" />
        <span>I will pick</span>
    </label>
</div>

然后脚本变为

var divs = $('.Add1').children('div');
$('.delivery input[type="radio"]').change(function() {
    var id = $(this).data('divid');
    divs.hide(); // hide all
    $('#' + id).show();
});

并将您的第2和第3个div设置为最初隐藏的

.Add1 div:not(:first-of-type) {
  display:none;
}

参考updated fiddle