我正在客户的 WordPress 网站上使用 WP-Properties 插件。价格需要用逗号表示千。页面上的 HTML 为:
<li class="property_price">
<div>Price: </div> $54000.00 USD
</li>
您无法在插件管理中的价格中添加逗号,因为逗号指定下拉菜单中的行。所以我使用以下 JavaScript 来添加逗号:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
$(".property_price").each(function() {
var self = $(this), text = self.text();
self.text(addCommas(text));
});
这有效,但它也会删除 <div>
围绕标签,因此生成的 HTML 为:
<li class="property_price">
Price: $54,000.00 USD
</li>
如何调整 javascript,使其添加逗号并保留 <div>
?
最佳答案
您可以修改单个文本节点,而不是 <div>
元素。大多数 jQuery 方法从结果中排除文本节点( find()
、 children()
等),但 contents()
保留它们。
$(".property_price").each(function() {
var target = $(this).contents().last(), text = target.text();
target.replaceWith(addCommas(text));
});
关于Javascript 在价格中添加逗号而不删除 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23397608/