从li标签内的字符串替换/删除文本的最佳方法 [英] Best way to replace/remove text from a string inside an li tag
问题描述
我正在ExpressionExpress中的站点地图列表上工作(因此我对事情的呈现方式没有太多的灵活性),如果需要,我需要从字符串中删除父母"一词它存在.
I'm working on a sitemap list in ExpressionEngine (so I don't have too much flexibility on how things are rendered) and I need to remove the word 'Parent' from a string if it exists.
以下是HTML输出的示例:
Below is an example of HTML output:
<li class="sitemap-item">
<a href="">About Us Parent</a>
<ul>
<li class="sitemap-item">
<a href="">About Us</a>
<ul>
<li class="sitemap-item">
<a href="http://website.dev/about-us/meet-the-directors">Meet the Directors</a>
</li>
<li class="sitemap-item">
<a href="">Partners</a>
</li>
<li class="sitemap-item">
<a href="">Accreditation & Awards</a>
</li>
<li class="sitemap-item">
<a href="">Testimonials</a>
</li>
<li class="sitemap-item">
<a href="http://website.dev/careers">Careers</a>
</li>
</ul>
</li>
</ul>
</li>
我没有运气就尝试了以下jQuery,只是根本不替换单词:
I tried the following jQuery with no luck, just doesn't replace the word at all:
$(document).ready(function(){
if($('li:contains("Parent")')){
$(this).replace('Parent','');
};
});
如您所见,我正在尝试使用jQuery.任何人都可以阐明执行此操作的正确方法吗?
As you can see I'm trying to do this with jQuery. Can anyone shed some light on the correct way to do this?
推荐答案
jQuery没有replace
方法,它是字符串的本机方法,这意味着您必须首先将文本作为字符串,例如使用text()
,然后再次将更改后的字符串返回
jQuery doesn't have a replace
method, it's a native method for strings, meaning you have to get the text first as a string, for instance with text()
, and then return the changed string back again
$(document).ready(function(){
$('li > a:contains("Parent")').text(function(_, txt) {
return txt.replace('Parent','');
});
});
这篇关于从li标签内的字符串替换/删除文本的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!