简体   繁体   中英

JQuery, clone and append only if target div not already has div with id

I'm trying to clone and append a div to another div. But I only want to move it if the target div does not already contain a clone.

function addToPortFolio(cl) {           
        var className = cl.attr('id');      
        console.log(className);

        if ($(".portfolioWrapper").has("#" + className).length > 0){ 
            console.log('exists');    
        } else {
            cl.clone().appendTo('.portfolioWrapper');
            console.log('not exist');
        }
    }

Below is the console log:

not exist
AAA.L
not exist
AAA.L
not exist
AAAP
not exist
AAAP
exists
AAAP
exists
AAAP
exists

It's behaving very odd, and can't really figure out why. If I continously click the div with class AAA.L it will not work, but AAAP will?

Is this a general bad practise?

This should work:

function addToPortFolio(cl) {
  if ($(".portfolioWrapper").find($('.' + cl.className.replace(' ','.'))).length >  0){ 
    console.log('exists');    
  } else {
    cl.clone().appendTo('.portfolioWrapper');
    console.log('just added it');
  }
}

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