Javascript 如何过滤文本,以便将部分文本转换为货币?
我有一些数字需要转换成货币。我正在使用这个脚本进行转换(),它对我的一个数字有效,但对另一个数字无效。我无法确定如何将li中的数字作为目标(在这种情况下,我无法修改html输出)。我试图过滤文本以从li中的数字重新定位“:”,但仍然无法获得货币转换以处理li中的数字 我这里有一把小提琴: 这是我的html:Javascript 如何过滤文本,以便将部分文本转换为货币?,javascript,jquery,Javascript,Jquery,我有一些数字需要转换成货币。我正在使用这个脚本进行转换(),它对我的一个数字有效,但对另一个数字无效。我无法确定如何将li中的数字作为目标(在这种情况下,我无法修改html输出)。我试图过滤文本以从li中的数字重新定位“:”,但仍然无法获得货币转换以处理li中的数字 我这里有一把小提琴: 这是我的html: <ul class="cfeature"> <li class="purchase_price">
<ul class="cfeature">
<li class="purchase_price"><label>Purchase Price</label>: 333333</li>
</ul>
<p class="purchase_price">
<label>Purchase Price: </label>
<strong><span>333333.00</span></strong>
</p>
- 采购价格:333
购买价格:
333333.00
这是我的js:
$('.purchase_price').each(function() {
$(this).html($(this).html().replace(":", ""));
});
$('.purchase_price').each(function() {
$(this).html($(this).html().replace("Purchase Price", "Purchase Price:"));
});
$(".purchase_price span").currency(); // this one works as the number is in a <span>
$(".purchase_price").currency(); // this one doesn't work
});
});
$('.purchase_price')。每个(函数(){
$(this.html($(this.html().replace(“:”,”);
});
$('.purchase_price')。每个(函数(){
$(this.html($(this.html().replace)(“购买价格”,“购买价格:”);
});
$(“.purchase_price span”).currency();//这个数字在a中起作用
美元(“.purchase_price”).currency();//这个不行
});
});
您可以通过在
上循环并对每个循环执行以下3个步骤来解决此问题:
中,并给它一个类,比如说forCurrency
.currency()
应用于此
并获取相应的文本
替换为我们刚刚得到的文本jQuery:
$("ul.cfeature > li").each(function(){
// wrap the number in a div
$(this).html(function(_, html) {
return html.replace(/(\d+)\s*$/, "<div id='forCurrency'>$1</div>");
});
// apply .currency() and get the corresponding text
var currencyText = $("div#forCurrency").currency().text();
console.log(currencyText);
// replace the wrapped div with the text that we just got
$("div#forCurrency").replaceWith(currencyText);
});
$(“ul.cfeature>li”)。每个(函数(){
//把数字用div括起来
$(this).html(函数(\ux,html){
返回html.replace(/(\d+)\s*$/,“$1”);
});
//apply.currency()并获取相应的文本
var currencyText=$(“div#forCurrency”).currency().text();
console.log(currencyText);
//用我们刚刚得到的文本替换包装的div
$(“用于货币的div”)。替换为(currencyText);
});
如果这是您在该课程中拥有的唯一数字,则它可以工作:谢谢,但该数字是动态的,并且不会在
li
,并应用相同的逻辑,但使用的是一个ID,而不是像我们之前所做的那样使用一个类。看这把小提琴:答案更新了。谢谢Rahul!我已经接受了你的答案,但我不能放弃,因为我需要先提高我的声誉:)一旦我接受了,我一定会回来做这件事!