2015-10-16 44 views
2

我试图改变一个span标记 内文本的一部分,我想这:改变部分

<script> 
    $(document).ready(function(){ 
     var toreplace= $(".poly-items__price span"); 
     toreplace = toreplace.replace("change","<p>new text</p>"); 
     $(".poly-items__price span").html(toreplace); 
    }); 
</script> 

这里是一个html:

<div class="poly-items__price"> 
    <span>do not change change</span> 
</div> 

这里有一个例子我使用: http://jsfiddle.net/Scoobler/a9cvx/4/http://jsfiddle.net/bwhfD/

,但它不工作 你能告诉我是什么我错过了 感谢

回答

3

要想从$(".poly-items__price span")文本需要呼叫.text()(或.html()如果你关心里边跨度HTML标签)

$(document).ready(function(){ 
    var toreplace= $(".poly-items__price span").text(); 
    toreplace = toreplace.replace("change","<p>new text</p>"); 
    $(".poly-items__price span").html(toreplace); 
}); 

如果你想全部替换“变”使用:

toreplace = toreplace.replace(/change/g,"<p>new text</p>"); 

这里是一些小提琴http://jsfiddle.net/qsbdg4po/1

编辑

如果您有多个.poly-items__price跨度,使用每个循环:

$('.poly-items__price span').each(function() { 
    var toreplace = $(this).html(); 
    toreplace = toreplace.replace("change","<p>new text</p>"); 
    $(this).html(toreplace); 
}); 
+0

你不应该混'HTML()'和'文本()'。如果你使用'text()',设置'text()'(在这种情况下不起作用)。如果你使用'html()',设置'html()'(危险,因为在一般情况下)。 – Amadan

+0

谢谢,但它仍然无法正常工作 –

+0

@ front-end_junior它是检查,在小提琴:http://jsfiddle.net/qsbdg4po/1 – Sojtin

-1

试试这个

<script> 
    $(document).ready(function(){ 
    var toreplace= $(".poly-items__price span").html(); 
    toreplace = toreplace.replace("change","<p>new text</p>"); 
    $(".poly-items__price span").html(toreplace); 
    }); 
</script> 
<div class="poly-items__price"> 
<span>do not change change</span> 
</div> 
2

您也可以通过一个功能jQuery.html

$(document).ready(function(){ 
 
     $(".poly-items__price span").html(function() { 
 
       return $(this).html().replace("change","<p>new text</p>"); 
 
     }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="poly-items__price"> 
 
    <span>do not change change</span> 
 
</div>

1

试试这个

可以ALSE使用$(toreplace).find("span").html(str);更换跨度 的内容

$(document).ready(function(){ 
 
     var toreplace= $(".poly-items__price"); 
 
     var str = $(toreplace).find("span").text().replace("change","<p>new text</p>"); 
 
    $(toreplace).find("span").text(str); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="poly-items__price"> 
 
    <span>do not change</span> 
 
</div>