gpt4 book ai didi

javascript - 如何检测 ":"之前的单词并使用 jquery 包装在 "span"中?

转载 作者:搜寻专家 更新时间:2023-11-01 05:20:42 26 4
gpt4 key购买 nike

我正在尝试检测文本中的字符,如果找到,则将其前面的单词包装在 HTML 元素中,然后删除该字符。

示例:

Case:

成为

<span class="th">Case</span>

方法

我可以使用以下方法检测 : 的存在:

if (str.indexOf(':') > -1)

在我使用之前得到这个词:

var th = str.split(':')[0];

将单词包装在我尝试过的元素中:

var th_wrap = "<span class='th'></span>";  
$(th).wrap(th_wrap);

这是行不通的。要删除 : 我试过:

th.replace(':', '');

这也行不通。

为了让它稍微复杂一点,我想捕获 someword: 的任何出现,而不仅仅是第一个。

如果有任何指点,我将不胜感激。 (javascript 或 jQuery)

片段

var str = $('.target').html();
if (str.indexOf(':') > -1) {
var th = str.split(':')[0];
th.replace(':', '');
var th_wrap = "<span class='th'></span>";
$(th).wrap(th_wrap);
}
th { font-weight: bold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="target">
Case 1:
<br />some text
<br />some more text
<br />even more text
<br />
<br />Case 2:
<br />some text
<br />some more text
<br />even more text
</p>

最佳答案

在您的例子中,单词Case 1:Case 2: 是文本节点。

因此,您需要获取target 下的所有节点:为此,使用jQuery.contents() .

片段:

$('.target').contents().each(function(idx, ele) {
if (ele.nodeType == Node.TEXT_NODE &&
ele.textContent.indexOf(':') > -1) {
ele.textContent = ele.textContent.replace(':', '');
$(ele).wrap($('<span/>', {
class: 'th'
}));

}
});
.th {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<p class="target">
Case 1:
<br />some text
<br />some more text
<br />even more text
<br />
<br />Case 2:
<br />some text
<br />some more text
<br />even more text
</p>

关于javascript - 如何检测 ":"之前的单词并使用 jquery 包装在 "span"中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41899761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com