1

次のような余分な行と列をすべて削除して、テーブル構造を最適化する jQuery を作成しています。

  • a) 2 つ未満の子要素を含む
  • b)重複したコンテナーを含む ( .columncan't have child .column.rowcan't have child .row)

それでもうまくいきませんでした。6 つのステップで実行されます (コメントに表示されます)。

#exampleを に変えるには何が必要#solutionですか?

var selection;
//1. Select all rows and columns
selection = $('#example').find('.row, .column');
//2. Deselect rows and columns with more than 1 child
selection = selection.not('.row:has(div:nth-of-type(2)), .column:has(div:nth-of-type(2))');
//3. Deselect rows and columns that contain cells
selection = selection.not('.row:has(.cell:nth-of-type(1)), .column:has(.cell:nth-of-type(1))');
//4. Remove redundant divs
console.log(selection);
//selection.css('border', '1px yellow solid');//paint them yellow (for testing)
selection.children().first().unwrap();
//5. Select duplicate rows and columns
selection = $('#example').find('.row:has(.row), .column:has(.column)');
//6. Remove redundant divs since first removal
selection.children().first().unwrap();
.grid {
  display: flex;
  min-height: 5px;
}
.row {
  display: flex;
  flex-grow: 1;
  border: 1px solid red;
}
.cell {
  flex-grow: 1;
  flex-basis: 20px;
  border: 1px solid green;
}
.column {
  display: flex;
  flex-grow: 1;
  flex-direction: column;
  border: 1px solid blue;
}
.row,
.column,
.cell {
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span>Example</span>
<div id="example" class="grid">
  <div class="column">
    <div class="row">
      <div class="column">
        <div class="row">
          <div class="column">
            <div class="cell">
            </div>
          </div>
        </div>
      </div>
      <div class="column">
        <div class="row">
          <div class="cell">
          </div>
          <div class="cell">
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<span>Solution</span>
<div id="solution" class="grid">
  <div class="row">
    <div class="cell">
    </div>
    <div class="cell">
    </div>
    <div class="cell">
    </div>
  </div>
</div>

4

2 に答える 2

1

あなたが与えた式に基づいて、このデモを試してください

$('#example').find('.column').each(function(){
   $(this).find(".column").each(function(){
     $(this).unwrap();
   });
   if ($(this).children().size() < 2 && $(this).find(".cell").size() == 0 )
   {
      $(this).remove();
   }
});

$('#example').find('.row').each(function(){
   $(this).find(".row").each(function(){
     $(this).unwrap();
   });
   if ($(this).children().size() < 2 && $(this).find(".cell").size() == 0 )
   {
      $(this).remove();
   }
});
于 2016-03-08T10:55:23.770 に答える