我正在创建一个 jQuery 来通过删除所有额外的行和列来优化表结构:
- a) 包含少于 2个子元素
- b)包含重复的容器(
.column
不能有孩子.column
,.row
不能有孩子.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>