繁体   English   中英

更改跨度jQuery中的文本部分

[英]change part of text inside span jquery

我尝试更改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/

但这不起作用,你能告诉我我错过了什么吗?

要从$(".poly-items__price span")获取文本,需要调用.text() (如果您关心span内的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);
});

您还可以将函数传递给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> 

尝试这个

您还可以使用$(toreplace).find("span").html(str); 用于替换span的内容

  $(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> 

尝试这个

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM