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>

ロジックは、最終結果が次のようになるように、各.offdivを同じ番号クラスの.ondivの後に追加する必要があるというものです。

<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 divを複製しており、3つしかないはずの12の.offdivがありました。 。これが私のコードです:

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

デモ

これは、要素に数値を含むクラスが1つしかないという前提で機能します。また、クラスが数字afaikで始まることは許可されていないため、クラスとして数字を使用することはセレクターでうまく機能しない可能性があります。動作しない場合は、他の文字を追加してください。

于 2011-06-02T15:38:30.297 に答える
0

私はフェリックス・クリングスの答えが好きですが、私がそれを終えたという理由だけで私も投稿します。私はあなたが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 に答える