[英]JQuery, clone and append only if target div not already has div with id
我正在嘗試克隆一個div並將其附加到另一個div。 但我只想在目標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');
}
}
下面是控制台日志:
not exist
AAA.L
not exist
AAA.L
not exist
AAAP
not exist
AAAP
exists
AAAP
exists
AAAP
exists
它表現得很奇怪,無法真正弄清楚原因。 如果我連續單擊AAA.L類的div,它將不起作用,但是AAAP可以嗎?
這是普遍的壞習慣嗎?
這應該工作:
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.