簡體   English   中英

使用jquery在文本字符串之間包裝一些html標記

[英]wrap some html tag between string of text by using jquery

跨度內的這個文本是由php生成的,如果我要從每年添加標簽到文本結尾。 我不知道如何定位文本字符串來啟動jquery。

<!-- input: -->
<span class="price">RM1,088.00 Annually + RM10.00 Setup Fee (Free Domain)</span>

<!-- output: --> 
<span class="price">
  RM1,088.00 
  <small>Annually + RM10.00 Setup Fee (Free Domain)</small>
</span>

這里最好的解決方案是修改PHP代碼生成的輸出。

如果那是不可能的話,假設生成的字符串中的價格格式始終相同,您可以通過空格分割文本以創建數組並分離出值。 嘗試這個:

 $('.price').html(function() { var values = $(this).text().trim().split(' '); return values.shift() + '<small>' + values.join(' ') + '</small>'; }); 
 span small { display: block; color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="price">RM1,088.00 Annually + RM10.00 Setup Fee (Free Domain)</span> <span class="price">RM2,090,082.00 Annually + RM25.00 Setup Fee (Free Domain)</span> 

您可以使用Text#splitText將文本節點拆分為兩個,此時可以使用jQuery輕松地包裝第二個文本節點:

 $('.price').contents().each(function () { $(this.splitText(this.data.indexOf("Annually"))).wrap('<small>') }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- input: --> <span class="price">RM1,088.00 Annually + RM10.00 Setup Fee (Free Domain)</span> 

我想你可能想看一個jQuery wrapInner。

$('.price').wrapInner('<small></small>');

這將包含任何sup的文本與鏈接。

http://api.jquery.com/wrapInner/

我想你想要這個......

 $(function(){ var text = $(".price").text(); text = text.split("+"); console.log(text[0] + text[1]); $('.price').html(text[0] + "<small>" + text[1] + "</small>"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="price">RM1,088.00 Annually + RM10.00 Setup Fee (Free Domain)</span> 

您可以輕松地在第一個空間拆分,然后在第二個零件周圍附上小標簽,請參閱以下內容:

 var firstPart = $(".price").text().substr(0,$(".price").text().indexOf(' ')); var secondPart = $(".price").text().substr($(".price").text().indexOf(' ')+1); var result = firstPart + "<small>" + secondPart + "</small>"; $(".price").html(result); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- input: --> <span class="price">RM1,088.00 Annually + RM10.00 Setup Fee (Free Domain)</span> 

我希望它可以幫助你,再見。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM