首页 / 编程 jQuery 替换 class 的方法

jQuery 替换 class 的方法

原创 分类: 编程 2023-3-2 10:01 阅读量:2319
使用javascript动态切换dom的class是前端开发中常见的需求,今天我们就以选择支付方式的示例来学习一下jQuery是怎么实现这个效果的....

1、

// 添加新的样式,移除旧的样式
.addClass("new-class") .removeClass("old-class");

2、

// 修改class属性,直接替换原class
.attr("class","new-class");

3、

// 自动检测,有就移除,没有就添加
.toggleClass("class1");

实战:选择支付方式
单选支付方式

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jquery替换class</title>
    <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
</head>
<style>
    body {
        background-color: #F6F8FA;
    }

    .radio-default {
        display: inline-block;
        width: 14px;
        height: 14px;
        border-radius: 50%;
        border: 2px solid #5C5B5B;
    }

    .radio-active {
        display: inline-block;
        text-align: center;
        line-height: 1;
        width: 18px;
        height: 18px;
        border-radius: 50%;
        background-color: #ED8D3E;
    }

    .radio-active::after {
        content: '✓';
        color: #fff;
        font-size: 16px;
        font-weight: bold;
    }

    .paytype {
        display: flex;
        flex-direction: row;
        align-items: center;
        width: 315px;
        margin: 0 auto;
        background-color: #fff;
        border-radius: 10px;
        padding: 15px;
    }

    .product-price {
        height: 80px;
        line-height: 80px;
        padding-right: 10px;
        margin-right: 10px;
        border-right: 1px solid #eee;
    }

    .paytype-items {
        width: 100%;
    }

    .paytype-item {
        width: 100%;
        height: 30px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;
    }

    .paytype-item:nth-child(1) {
        border-bottom: 1px solid #eee;
    }
</style>

<body>
    <div class="paytype">
        <div class="product-price">¥122</div>
        <div class="paytype-items">
            <div class="paytype-item" id="wxpay">
                <span>xx支付</span>
                <span class="radio-default"></span>
            </div>
            <div class="paytype-item" id="otpay">
                <span>xx支付</span>
                <span class="radio-default"></span>
            </div>
        </div>
    </div>
</body>
<script>
    (function () {
        $("#wxpay").click(function () {
            $("#otpay span:nth-child(2)").attr("class", "radio-default");
            $(this).find("span:nth-child(2)").attr("class", "radio-active");
        });
        $("#otpay").click(function () {
            $("#wxpay span:nth-child(2)").attr("class", "radio-default");
            $(this).find("span:nth-child(2)").attr("class", "radio-active");
        })
    })()
</script>

</html>