[英]Wrap/Break List elements by replace text to class
我的問題是如何通過從列表項文本中添加類查找來包裝/打破列表項,下面的示例?
我的相關問題是: Wrap List elements by class name
<div class="widget-content">
<ul>
<li><span class="label"> demo-text1 </span> Test Content</li>
<li><span class="label"> demo-text2 </span> Test Content</li>
<li><span class="label"> demo-text1 </span> Test Content</li>
<li><span class="label"> demo-text2 </span> Test Content</li>
<li><span class="label"> demo-text1 </span> Test Content</li>
<li><span class="label"> demo-text2 </span> Test Content</li>
</ul>
</div>
我想打破這樣的列表項:
<div class="widget-content">
<ul class="demo-text1">
<li><span class="label"> demo-text1 </span> Test Content</li>
<li><span class="label"> demo-text1 </span> Test Content</li>
<li><span class="label"> demo-text1 </span> Test Content</li>
</ul> <!-- Break part 1 -->
<ul class="demo-text2">
<!-- Break part 2 -->
<li><span class="label"> demo-text2 </span> Test Content</li>
<li><span class="label"> demo-text2 </span> Test Content</li>
<li><span class="label"> demo-text2 </span> Test Content</li>
</ul>
</div>
我的意思是將列表項分為兩部分,例如第二個 HTML 示例。 通過替換上面給出的class="label"
示例(第二個 HTML)中的文本查找,將class="label"
添加到父ul
。
我怎么能簡單地通過 jQuery/JS 做到這一點? 這是我嘗試過的:
$(".widget-content").each(function() {
var $li = $(this).find("li").unwrap(); // unwrap removes the old UL wrapper
var uniq = [];
// Create a collection of unique "label*" classes:
$li.find("[class^=label]").attr("class", function(i, v) {
if (!~$.inArray(v, uniq)) uniq.push(v);
});
// Group LI by A class, and wrap into a new UL with the same class
$.each(uniq, function(i, klas) {
$("a." + klas).closest("li").wrapAll($("<ul/>", {
class: klas
}));
});
});
提前致謝。
你可以使用.each()
, $.each()
, .html()
, .text()
, .trim()
var arr = []; // array to store `li` elements var widget = $(".widget-content"); $(".widget-content li").each(function(index, el) { var html = el.outerHTML; // number at `label` text var curr = $(".label", this).text().trim().slice(-1); if (arr[curr - 1]) { arr[curr - 1].push(html) } else { arr[curr - 1] = [html]; } }); widget.html(""); // remove existing `html` $.each(arr, function(key, val) { var li = val.join(""); $(".widget-content").append($("<ul/>", { html: li, "class":$(li).eq(0).find(".label").text().trim() })) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div class="widget-content"> <ul> <li><span class="label"> demo-text1 </span> Test Content</li> <li><span class="label"> demo-text2 </span> Test Content</li> <li><span class="label"> demo-text1 </span> Test Content</li> <li><span class="label"> demo-text2 </span> Test Content</li> <li><span class="label"> demo-text1 </span> Test Content</li> <li><span class="label"> demo-text2 </span> Test Content</li> </ul> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.