2011-06-02 39 views
2

所以服务器给了我一个隐藏输入内的html块。我需要采取这个块(其中包含多个div),并移动这些div,但有一些逻辑。jquery每个问题

我的做法是把隐藏的输入(HTML块)的值,并将其添加到一个新创建隐藏的div:

var history = $("input[name=history]").val(); 
    $("#global_wrapper").after("<div id='history_temp' style='display:none;'></div>"); 
    $("#history_temp").html(history); 

这里是什么样的HTML块看起来像一个例子:

<div class="off 1"></div> 
<div class="off 1"></div> 
<div class="off 2"></div> 
<div class="off 3"></div> 

的.off将永远存在和数量类的范围从1-9

基于数类,我需要每个这些div的移动到现有的HTML块看起来像这样:

<div class="on 1"></div> 
<div class="on 2"></div> 
<div class="on 3"></div> 

的逻辑是,每个.off DIV需要与相同数目的类。对DIV后要追加,使得最终的结果是这样的:

<div class="on 1"></div> 
<div class="off 1"></div> 
<div class="off 1"></div> 
<div class="on 2"></div> 
<div class="off 2"></div> 
<div class="on 3"></div> 
<div class="off 3"></div> 

我的尝试是为每个.off div运行每个函数,然后为每个数字div设置一个if this.hasClass,但它复制了.off divs,并且有12个.off divs,当应该只是这是我的代码:

$("#history_temp .off").each(function(){ 
    if ($(this).hasClass("1")) { 
     $(this).clone().insertAfter(".on.1"); 
    } 
    else if ($(this).hasClass("2")) { 
     $(this).clone().insertAfter(".on.2"); 
    } 
    else if ($(this).hasClass("3")) { 
     $(this).clone().insertAfter(".on.3"); 
    } 
    else if ($(this).hasClass("4")) { 
     $(this).clone().insertAfter(".on.4"); 
    } 
    else if ($(this).hasClass("5")) { 
     $(this).clone().insertAfter(".on.5"); 
    } 
    else if ($(this).hasClass("6")) { 
     $(this).clone().insertAfter(".on.6"); 
    } 
    else if ($(this).hasClass("7")) { 
     $(this).clone().insertAfter(".on.7"); 
    } 
    else if ($(this).hasClass("8")) { 
     $(this).clone().insertAfter(".on.8"); 
    } 
    else if ($(this).hasClass("9")) { 
     $(this).clone().insertAfter(".on.9"); 
    } 
    else { 
     return false; 
    } 
    }); 

任何人都可以指向正确的方向吗?我很好奇最有效的解决方案是什么。

感谢, 布赖恩

编辑:固定在我的示例代码中的错误( “” 被失踪前,各阶级)

回答

3

FWIW,你的代码工作正常:http://jsfiddle.net/7XWuN/2/

我假设您没有发布的代码中还有其他内容正在发生。

没有任何更多的情况下,我建议是这样的:

$("#history_temp .off").each(function(){ 
    var n = this.className.match(/\d+/)[0]; 
    $(this).insertAfter('.on.' + n); 
}); 

DEMO

这个工程的假设元素具有包含一些只有一个类下。也可能是因为使用数字作为类对选择器不起作用,因为类不允许以数字afaik开头。如果不起作用,请添加其他字符。

+0

谢谢!这比我的效率更高,额外的循环消失了(我认为是克隆造成的)。 – brianandrich 2011-06-02 15:48:45

+0

@brianandrich:看到我的更新,你的代码工作正常。也许'history_temp' div没有隐藏? – 2011-06-02 15:49:31

+0

是的,代码比这复杂得多。还有其他问题导致问题 – brianandrich 2011-06-02 15:50:01

0

我喜欢Felix Klings的回答更好,但是我发帖子的时候也是因为我完成了。我只是假设你有1-9级的课程,如果你碰巧超越了9级,并且更加优化,他会更具包容性。

Live Demo

$("#history_temp .off").each(function(){ 
     for(var i=1; i < 10; i++){ 
      if ($(this).hasClass(i)) { 
       $(this).clone().insertAfter(".on." + i); 
      } 
     } 
    }); 
+0

谢谢,Loktar。非常感激 – brianandrich 2011-06-02 15:49:00