[英]find matching words and underline them - but just the words
I have this code where I'm trying to search and underline all instances of a specified word:我有这段代码,我试图在其中搜索和下划线指定单词的所有实例:
$(".test:contains('moon')").css("text-decoration", "underline");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="test">The cow jumped over the moon</div>
The above is underlining the whole text.以上是全文的下划线。
How can I get it to underline just the instances of "moon"?我怎样才能让它只强调“月亮”的实例?
Iterate over each element and .replace
its innerHTML
:遍历每个元素并
.replace
它的innerHTML
:
$(".test:contains('moon')").each(function() { this.innerHTML = this.innerHTML.replace(/moon/g, '<span style="text-decoration: underline">moon</span>'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="test">The cow jumped over the moon</div>
With your current code, you are applying the style to the whole element
that contains the searched word
.使用您当前的代码,您将样式应用于包含搜索
word
的整个element
。
You need to loop through all the matched words and replace them accordingly with the desired style in the html
of the containing element
:您需要遍历所有匹配的单词,并在包含
element
的html
它们相应地替换为所需的样式:
let word = 'moon'; $(".test:contains('" + word + "')").each(function() { let regex = new RegExp("(" + word + ")", 'g'); $(this).html($(this).text().replace(regex, '<span style="text-decoration: underline">$1</span>')); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <div class="test">The cow jumped over the moon</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.