简体   繁体   中英

Jquery ajax change class clicked by data-id

i have one question about jquery on click.

This is DEMO from jsfiddle.net

When you click the demo you can see there is a green and yellwo div.

The question is when you click the data-id="1" and change this div class:

<div class="icon-kr icon-globe"></div>

change icon-globe to icon-contacs

and when you click data-id="2" then change:

change icon-globe to icon-lock-1

also same think is for data-id="0" How can i do that anyone can help me in this regard ? HTML

<div class="container" id="1">
    <div class="icon_ar"><div class="icon-kr icon-globe"></div>1</div>
    <div class="pr_type">
        <div class="type_s change_pri" data-id="0"><div class="icon-pr icon-globe"></div>1</div>
        <div class="type_s change_pri" data-id="1"><div class="icon-pr icon-contacs"></div>2</div>
        <div class="type_s change_pri" data-id="2"><div class="icon-pr icon-lock-1"></div>3</div>
    </div>
</div>

JS

$('.change_pri').click(function(){
    var dataid = $(this).attr('data-id');
    var id = $(this).closest('.container').attr('id');
    $.ajax({
        type: "POST",
        url: "chage_number.php",
        data: { dataid : dataid, id: id }
    }).success(function(result){
        alert(result);
    });
});

One way to do this is below. I have only done the class changing bit based on click. I am not sure about your ajax code. Let me know if you need further help.

$('.change_pri').click(function(){

    var class_name = $(this).find(".icon-pr").attr("class");
    class_name = class_name.replace(/icon\-pr\s+/gi, "");
    $(this).closest(".container").find(".icon-kr")
    .removeClass().addClass("icon-kr " + class_name);
});

Updated fiddle

You need to use .data(), you are not accessing the data correctly. https://api.jquery.com/jquery.data/

var dataid = $(this).data('id');

You are accessing this data-* attribute incorrectly, Use this,

$('.change_pri').click(function(){
    var dataid = $(this).data('id');
        $(this).parent().siblings('.icon_ar').find('div').removeClass("icon-globe icon-contacs icon-lock-1");
        if(dataid=="0")
        {
             $(this).parent().siblings('.icon_ar').find('div').addClass("icon-globe");
        }
        else if(dataid==1)
        {
             $(this).parent().siblings('.icon_ar').find('div').addClass("icon-contacs");
        }
        else
        {
             $(this).parent().siblings('.icon_ar').find('div').addClass("icon-lock-1");
        }


//AJAX CODE.
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM