我想使用javascript/jquery从字符串中的第一个唯一单词插入一个标记。它有点像:
jQuery(document).ready(function($){
$(".product_title:contains(NEW)").replace('NEW', '<span class="new">NEW</span>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
FROM: <h2 class="product_title">NEW Jeep Wrangler</h2>
INTO: <h2 class="product_title"><span class="new">NEW</span>Jeep Wrangler</h2>
FROM: <h2 class="product_title">REBUILT Jeep Wrangler</h2>
INTO: <h2 class="product_title"><span class="rebuilt">REBUILT</span>Jeep Wrangler</h2>
我尝试了以下方法用html代码替换第一个单词,但没有成功:我在控制台上收到了一个Uncaught TypeError: $(...).replace is not a function
。
如何做到这一点?我在网上找不到任何应用这种类似方法的例子。请告知。
更新:我认为我已经接近了,我使用以下方法:
$('.product_title').each(function() {
var text = $(this).text();
$(this).text(text.replace('NEW', '<span class="cust-woo-title-tag-new">NEW</span>'));
});
但是标签显示在前端。
- 获取包含"NEW">
- 存储以前的html值(例如
NEW Jeep Wrangler
( - 删除";NEW";单词(
NEW Jeep Wrangler
变成吉普牧马人( - 更新
innerHTML
$(document).ready(function($){ //get all the product_title that contains "NEW" let contains_new = $(".product_title:contains(NEW)"); for(let x = 0; x < contains_new.length; x++) { //store the previous html value let prev_html = contains_new[x].innerHTML; //remove the "NEW" word in the prev_html let new_html = prev_html.replace('NEW',''); //update the inner html contains_new[x].innerHTML = `<span class"new">NEW</span>${new_html}`; } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h2 class="product_title">NEW Jeep Wrangler</h2> <h2 class="product_title">NEW Jeep Wrangler</h2>
尝试检查元素的结果以查看html
结构
类似的东西可以工作:
$('h2').each((i)=>{
txt=$(i).text().split(' ')
i_html = `
<span class ='${txt[0]}.toLocaleLowerCase()' >${txt.pop(0)}</span> ${txt.join(' ')}
`
$(i).html(i_html)
})
如果您只想对某些单词执行此操作,请使用它们创建一个数组,并使用keywords.include(txt[0])
进行检查