如何更改类属性的值

时间:2014-10-31 11:11:10

标签: jquery

根据文字的不同,我正在尝试更改span类的值

我的代码:

$(document).on('click', '#deactivebtn', function (event) {
    var $checked = $('#customer_details_table').find(":radio:checked");
    var id = $checked[0].id;
    var val = $("#" + id).closest('tr').find('span').text();
    if (val == 'Active') {
        $("#" + id).closest('tr').find('span').attr('class') = 'label label-success';
    }
   else if (val == 'DeActive') {
        $("#" + id).closest('tr').find('span').attr('class') = 'label label-inverse';
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table table-striped table-bordered table-hover dataTable" id="customer_details_table" aria-describedby="sample_1_info" style="display: table;">
    <thead>
        <tr>
            <th></th>
            <th>Customer Name</th>
            <th>Address</th>
            <th>Contact No.</th>
            <th>Email</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody class="odd gradeX">
        <tr>
            <td>
                <label class="radio">
                    <input type="radio" class="bradio" id="20" name="optionsRadios1" value="option1">
                </label>
            </td>
            <td width="20%">kiran</td>
            <td width="25%">XXXXXXX</td>
            <td width="20%">7654321987</td>
            <td width="20%">venkatrajkiran@yahoo.com</td>
            <td width="10%" align="center"><span class="label label-inverse">Active</span>
            </td>
        </tr>
        <tr>
            <td>
                <label class="radio">
                    <input type="radio" class="bradio" id="28" name="optionsRadios1" value="option1">
                </label>
            </td>
            <td width="20%">kiran</td>
            <td width="25%">XXXXXXX</td>
            <td width="20%">9701429843</td>
            <td width="20%">s@g.com</td>
            <td width="10%" align="center"><span class="label label-inverse">DeActive</span>
            </td>
        </tr>
    </tbody>
</table>
<button type="button" id="deactivebtn" class="btn blue" style="display: inline-block;">Click</button>

JSFiddle:http://jsfiddle.net/mjvoavrc/4/

1 个答案:

答案 0 :(得分:0)

您可以使用.hasClass

进行查询
$(document).on('click', '#deactivebtn', function (event) {
    var $checked = $('#customer_details_table').find(":radio:checked");
    var id = $checked[0].id;
    var span = $("#" + id).closest('tr').find('span');
    if (span.hasClass('label-inverse')) {
        span.removeClass('label-inverse').addClass('label-success');
    }
   else if (span.hasClass('label-success')) {
        span.removeClass('label-success').addClass('label-inverse');
    }
});

<强>参考文献:

http://api.jquery.com/hasclass/

http://api.jquery.com/addclass/

http://api.jquery.com/removeclass/