1

为什么我的功能不起作用:

小提琴

HTML:

<div class="cash">1234.00</div>
<div class="cash">123456.00</div>
<div id="total"></div>

JS:

function formatPrice(price) {
    return price.reverse().replace(/((?:\d{2})\d)/g, '$1 ').reverse();
}

// Need to extend String prototype for convinience
String.prototype.reverse = function() {
    return this.split('').reverse().join('');
}

$('.cash').each(function(){
    $(this).html().formatPrice().appendTo('body');
});

我也试过这个,没有运气:

$('.cash').each(function(){
    $(this).html() = i;
    formatPrice(i).appendTo('body');
});

即使将其剥离为基本功能,它仍然不会附加我的东西......我失去了我的魔力吗?

$('.cash').each(function(){
    $(this).html().appendTo('body');
});

谢谢

更新:该功能只是假设这样做:

formatPrice('1234.00') //转换为“1 234.00” formatPrice('123456.00') //转换为“123 456.00”

4

2 回答 2

7

为了使您的示例正常工作,您应该修复这部分代码:

$('.cash').each(function(){
    $('body').append(formatPrice($(this).html()));
});

这是小提琴

您不能 run html().formatPrice(),因为formatPrice()在您的情况下是独立函数,而不是字符串对象的方法。

如果要替换里面的文字div.cash,请使用以下代码:

$('.cash').each(function(){
    $(this).html(formatPrice($(this).html()));
});

这是更新的小提琴

如果您希望能够formatPrice()用于任何字符串,请执行以下操作:

String.prototype.formatPrice = function() {
    return this.reverse().replace(/((?:\d{2})\d)/g, '$1 ').reverse();
}

$('.cash').each(function(){
    $(this).html(function(i, h) { return h.formatPrice() });
});

这是小提琴

因此,只需选择您喜欢的选项并使用它。

于 2013-04-17T19:25:17.800 回答
4

$(this).html()返回文本中的 html,而不是包含该appendTo函数的 jQuery 对象。

你可以做:

$($(this).html()).appendTo('body');

顺便说一句,您不应该“选择 html”并假设将其传递给您的formatPrice函数是安全的。

这样做,它更干净:

<div class="cash" data-cash="1234.00">1234.00</div>

$('body').append(formatPrice($(this).attr("data-cash")));
于 2013-04-17T19:23:53.720 回答