[英]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的文本与链接。
我想你想要这个......
$(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.