[英]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. 我正在尝试克隆一个div并将其附加到另一个div。 But I only want to move it if the target div does not already contain a clone. 但我只想在目标div尚未包含克隆的情况下移动它。
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? 如果我连续单击AAA.L类的div,它将不起作用,但是AAAP可以吗?
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');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.