简体   繁体   中英

Prevent Matched data from being published using If statement in $each function

In this $each function I have json array data coming from a Ajax call. What I am trying to do is; If the data coming from the ajax array contains the same unique name as the (current visible data to the online user. eg in Divs classes) Alert it. That works it sends an alert.

The thing I want to do is prevent the data from going through after the alert if a match is found. I appriciate any help thank you. The alert is there to confirm match finding is working. I also use $grep so if the solution lies there I am happy to use that.

     Var data = [data from ajax]

     $.each(data, function( i, record ) {
     
     var getname = $(self).closest('.client').find('.name').html();
     if ( getname == record.name){
      alert("duplicate");
     }

Rather than messing with the DOM that much, it might be worth maintaining an array of IDs of the DIVs that are being added to the page. As you do your data pull, see if the ID exists in the array and if not add the ID to the array and append the new DIV to the page. This way you never have to worry about removing anything.

var objects = {};

$.each(data, function( i, record ) {

    // Using the array to track records
    if (!(record.id in objects)){
        objects[record.id] = record;
        
        // create and add element to page
    }

    
    // OR....


    // Searching the DOM for the element
    if(!document.getElementById(record.id)){
    
        // create and add element to page
    }
}

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