【问题标题】:Jquery add class to div on different buttonJquery将类添加到不同按钮上的div
【发布时间】:2021-01-10 06:58:30
【问题描述】:

我有一个按钮组,想根据按钮点击显示不同的 div。

如果我点击 purchase 按钮,如果我点击 I拥有许可证,它应该使用 isactive 类激活 license div,并隐藏 cadpaymentform div。

<div class="pricing5 py-5">
<div class="btn-group rounded-pill" data-toggle="buttons">
            <label class="btn btn-outline-secondary btn-md rounded-left active">
                            <input type="radio" name="options" id="option1" checked=""> <b>Purchase</b>
                        </label>
            <label class="btn btn-outline-secondary rounded-right btn-md">
                            <input type="radio" name="options" id="option2"> <b>I have a license</b>
                        </label>
          </div>
<div class="cadpaymentform isactive">
    form
</div>
<div class="license">
    license
</div>
          </div>

到目前为止,我已经尝试过这段代码,但不起作用

$(".pricing5 .btn-group .btn").click(function () {
            $(this).closest('.pricing5').find('.cadpaymentform').removeClass('isactive');
            $(this).closest('.pricing5').find('.license').addClass('isactive');
        });

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    使用此代码。

    /*$(".pricing5 .btn-group .btn").click(function () {
                $(this).closest('.pricing5').find('.cadpaymentform').removeClass('isactive');
                $(this).closest('.pricing5').find('.license').addClass('isactive');
            });*/
    
    $('.pricing5 .btn-group .btn input[name="options"]').on('change', function(e) {
       var className = e.target.value;
       $(this).closest('.pricing5').find('.view').removeClass('isactive');
       $(this).closest('.pricing5').find('.view.' + className).addClass('isactive');
    });
    .cadpaymentform, .license {
     display: none;
    }
    
    .isactive {
     display: block;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="pricing5 py-5">
    <div class="btn-group rounded-pill" data-toggle="buttons">
                <label class="btn btn-outline-secondary btn-md rounded-left active">
                                <input type="radio" name="options" id="option1" value="cadpaymentform" checked=""> <b>Purchase</b>
                            </label>
                <label class="btn btn-outline-secondary rounded-right btn-md">
                                <input type="radio" name="options" id="option2" value="license"> <b>I have a license</b>
                            </label>
              </div>
    <div class="view cadpaymentform isactive">
        form
    </div>
    <div class="view license">
        license
    </div>
              </div>

    【讨论】:

    • 没有问题。只要你有收音机,最好使用收音机 onchange 事件而不是点击
    猜你喜欢
    • 2010-12-01
    • 1970-01-01
    • 2022-12-01
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多