简体   繁体   中英

how to validate object in jquery

I am adding arbitrary data to li element using jquery as:

  if($("li").data('family').$(this).text()==$(this).text()){
        $("li").removeData('family',{'persons':''}); // I know this is wrong!
        // any idea how to remove data from this object 
    }else{
        //this part adds data which is not working fine 
        $("li").data('family',{$(this).text():$(this).text(),
            'cat':'family'
        });
    } 

above I m trying to validate whether the value already exits or not if exits remove it. I am facing 1 problem:

  1. How to add / remove key value same from object

Thanks in advance!

Try this:

var key='';
$(document).ready(function(){

    $("#cat-family ul li").on("click",function(){
    var $li=$(this);
    key=$(this).text();
    if($(this).data('family')){
        if($(this).data('family').key==$(this).text())
             $(this).removeData('family');        
    }
    else{  
        key=$li.text();
        var k={};
        k[key]=key;
        k['cat']='fam';

        $(this).data('family',k);
    } 
       console.log($(this).data());  
});
}); 

Read Docs http://api.jquery.com/removeData/

Fiddle http://jsfiddle.net/WmLQa/1/

Try this

$("#cat-family ul li").live("click", function() {
            var $ul = $(this).closest('ul');
            var family = $ul.data('family');
            if (!family) {
                family = {
                    'cat' : 'family'
                };
                $ul.data('family', family);
            }

            var text = $(this).text();
            if (family[text]) {
                delete family[text];
            } else {
                family[text] = text;
            }
            console.log(this, $ul.data().family);
        });

Demo: Fiddle

you can check data by:

 if($("li").data("family").persons === $(this).text())
 {
     $.removeData($("li") , "family"); //to remove
 }

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