試圖在每個 td 單元格中包裝“,”之前的所有單詞。請注意,每個單元格中“,”之前的單詞會有所不同,因此不能針對特定單詞本身
現有的html
<td class="name">
<a href="" title="" class="">lastName, firstName</a>
</td>
期望的結果
<td class="name">
<a href="" title="" class=""><span>lastName</span>, firstName</a>
</td>
嘗試,所有這些都破壞了 a href 結構,我需要按a原樣保留帶有 class、title 和 href的標簽,并將單詞/單詞包裹在“,”之前
$('td.name').each(function() {
$(this).html($(this).text().replace(/,.*$/, '<span >$&</span>'));
});
$('td.name').html(function(i, v) {
return v.replace(/([^,] )(,)/, '$1<span >$2</span>$3');
});
$('td.name').html(function (i, html) {
return html.replace(/(.*?,)/, '<span>$1</span>')
});
uj5u.com熱心網友回復:
您可以為每個節點創建一個TreeWalker<td>并使用它來查找所有文本節點,傳入過濾器以僅查找包含逗號的節點。
從那里,您可以將文本拆分成塊并將每個前逗號塊映射到一個新的塊,<span>然后用新的節點集替換整個文本節點。
const createSpan = textContent => Object.assign(
document.createElement("span"),
{ textContent }
)
const filter = {
acceptNode: node =>
node.data.includes(",") ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT
}
document.querySelectorAll("td.name").forEach(td => {
const treeWalker = document.createTreeWalker(
td,
NodeFilter.SHOW_TEXT, // select only text nodes
filter, // filter for content with commas
false
)
let node
while (node = treeWalker.nextNode()) {
// split the text on comma, keeping the delimiter
const chunks = node.data.split(/(?=,)/)
// keep the last chunk as-is
const last = chunks.pop()
// replace the text node with the new node set
node.replaceWith(...chunks.map(createSpan), last)
}
})
span { color: red; }
<table border="1">
<tr>
<td class="name">
<a href="" title="" class="">lastName, firstName</a>
</td>
</tr>
<tr>
<td class="name">
<a href="" title="" class="">no commas</a>
</td>
</tr>
</table>
我真的沒有看到 jQuery 在這里有任何用處。
uj5u.com熱心網友回復:
很高興您喜歡 jQuery,這幾行代碼將助您一臂之力。干杯!
$('.my_name').each(function() {
var my_text = $(this).find("a").text();
var my_wrap = my_text.replace(/[^,]*/, '<span >$&</span>');
$(this).find("a:contains(',')").empty().append(my_wrap);
});
.my_class { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<table>
<tbody>
<td class="my_name">
<a href="my_href.com" title="" class="">lastName, firstName</a>
</td>
<td class="my_name">
<a href="my_href.com" title="" class="">td 2 not affected</a>
</td>
</tbody>
</table>
//Output
<a href="my_href.com" title="" class=""><span class="my_class">lastName</span>, firstName</a>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348604.html
標籤:查询
