我在 span 类中有两个文本字符串,我需要使用 jQuery 或 vanilla Javascript 删除其中的一部分。字符串是#AAA 和#AAB
我之前使用过一些变体来实现这个结果,但是在这个跨度类上它似乎不起作用。
这是我尝试过的脚本:
$j('document').ready(
function() {
$j(”span.sku").text(function() {
return $(this).text().replace(/(#AAA |#AAB)/g, "");
}).addClass(”remove");
});
和
$j('body').ready(function(){
$j( ”span.sku:contains('#AAA')" ).addClass( ”remove" );
$j( ”span.sku:contains('#AAB')" ).addClass( ”remove" );
});
最后一个我尝试设置一个可以用 CSS 隐藏的类。
$j 用于站点正在使用的非冲突模式。
HTML:
<div class="product_meta">
<span class="sku_wrapper">SKU: <span class="sku" itemprop="sku">K1J2AEA#AAA</span></span>
<meta itemprop="brand" content="HP">
<meta itemprop="gtin14" content="">
<meta itemprop="itemCondition" itemtype="http://schema.org/OfferItemCondition" content="http://schema.org/NewCondition">
<span class="posted_in">Categorie: <a href="/category/computers/notebooks/" rel="tag">Notebooks</a></span>
</div>
最佳答案
您需要使用 '
或 "
作为字符串文字,还需要删除正则表达式中的 (空格)
var $j = jQuery.noConflict(true);
$j(function($) { //dom ready handler receives a jQuery object reference as its parameter so you can assign it ti $ and use it inside the handler
$("span.sku").text(function(i, text) {
return text.replace(/#AAA|#AAB/g, "");
}).addClass('remove');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="product_meta">
<span class="sku_wrapper">SKU: <span class="sku" itemprop="sku">K1J2AEA#AAA</span></span>
<meta itemprop="brand" content="HP">
<meta itemprop="gtin14" content="">
<meta itemprop="itemCondition" itemtype="http://schema.org/OfferItemCondition" content="http://schema.org/NewCondition">
<span class="posted_in">Categorie: <a href="/category/computers/notebooks/" rel="tag">Notebooks</a></span>
</div>
关于javascript - 如何删除 span 类中文本字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31740994/