[英]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.