Jquery 查询:检测是否已克隆具有特定数据属性的元素
每个任务(li.正在运行)都有自己的唯一ID应用于数据任务ID属性中。代码应该将每个任务复制到一个临时div(.helper timers)中,但是如果任务已经被克隆并且存在于.helper timers中,则显然不需要再次复制它Jquery 查询:检测是否已克隆具有特定数据属性的元素,jquery,clone,each,Jquery,Clone,Each,每个任务(li.正在运行)都有自己的唯一ID应用于数据任务ID属性中。代码应该将每个任务复制到一个临时div(.helper timers)中,但是如果任务已经被克隆并且存在于.helper timers中,则显然不需要再次复制它 解决了的 对于任何想知道的人,我都是这样设法解决的。 $(".sect-tasklist li.is-running").each(function(){ var $this = $(this), taskID = $(
解决了的 对于任何想知道的人,我都是这样设法解决的。
$(".sect-tasklist li.is-running").each(function(){
var $this = $(this),
taskID = $(this).data("task-id");
if ( /*if elem has already been cloned*/ ) {
console.log("already cloned, don't clone it again");
} else {
$(this).clone().appendTo(".helper-timers");
}
});
然后,我获取任务的部分功能包括:
(function(){
jQuery.fn.cloneRunningTimers = function() {
$(".sect-tasklist li.is-running").each(function(){
var $this = $(this),
taskID = $this.data("task-id");
if ( $(".helper-timers li.task-id-" + taskID).length ) { // if exists
// already cloned, don't clone again
} else { // if doesn't exist
$this.clone().appendTo(".helper-timers"); // clone
}
});
}; // fn cloneRunningTasks
})();
据我所知,这确保了同一任务不会同时出现在两个位置。您可以使用
jquery
的data
功能标记已处理(克隆)的元素
例如:
$(".helper-timers li").each(function(){
var $this = $(this),
taskID = $this.data("task-id");
if ( $(".sect-tasklist li.task-id-" + taskID).length ) { // if exists it task list
$this.remove(); // delete it from helper list
}
});
$this.data('cloned')
将返回数据字段cloned
,$this.data('cloned',true)
将数据字段设置为true
。(注意:克隆的
是一个任意名称,您可以使用任意名称。)您可以创建已克隆任务ID的外部引用,如下所示:
if ($this.data('cloned')) {
console.log("already cloned, don't clone it again");
} else {
$this.data('cloned', true);
$this.clone().appendTo(".helper-timers");
}
你能提供标记或制作fiddle吗?问题是。正在运行的列表不断变化(它被ajax覆盖),因此,即使我将“克隆”添加到项目中,当我需要它时,它也不会在那里。我想我可以利用已经存在的数据任务id attr,因为它包含每个任务的唯一编号。然后,当它被复制时,以某种方式使用jquery来检测页面上是否只存在该数字的一个或两个实例。对此有何想法?
var alreadyCloned = [];
$(".sect-tasklist li.is-running").each(function(){
var $this = $(this),
taskID = $(this).data("task-id");
if ( $.inArray(taskID, alreadyCloned) > -1 ) {
console.log("already cloned, don't clone it again");
} else {
alreadyCloned.push(taskID);
$this.clone().appendTo(".helper-timers");
}
});