2

所以服务器在隐藏的输入中给了我一个 html 块。我需要使用这个块(包含多个 div)并移动这些 div,但需要一些逻辑。

我的方法是获取隐藏输入(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 都需要附加在具有相同数字类的 .on 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 运行一个 each 函数,然后为每个数字 div 设置一个 if this.hasClass,但它正在复制 .off div,并且应该只有 3 个 .off div 有 12 个.这是我的代码:

   $("#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;
    } 
  }); 

谁能指出我正确的方向?我很好奇最有效的解决方案是什么。

谢谢,布赖恩

编辑:修复了我的示例代码中的一个错误(在每个班级之前都缺少“。”)

4

2 回答 2

3

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

我认为您未发布的代码中还有其他内容。

如果没有更多的上下文,我会建议这样的事情:

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

演示

这是在元素只有一个包含数字的类的假设下工作的。也可能是使用数字作为类不能很好地与选择器配合使用,因为类不允许以数字 afaik 开头。如果它不起作用,请在前面添加一些其他字符。

于 2011-06-02T15:38:30.297 回答
0

我更喜欢 Felix Klings 的回答,但我也会发布我的,因为我完成了它。我的只是假设你有名为 1-9 的类,如果你碰巧超过 9,他的类会更全面,并且更优化。

现场演示

   $("#history_temp .off").each(function(){
       for(var i=1; i < 10; i++){
             if ($(this).hasClass(i)) {
               $(this).clone().insertAfter(".on." + i);
             }
       }
  }); 
于 2011-06-02T15:42:15.710 回答