【问题标题】:Replace comma with period jQuery [duplicate]用句点jQuery替换逗号[重复]
【发布时间】:2014-07-27 01:52:58
【问题描述】:

我需要用句点替换每个 <li> 值中的逗号。

我不知道我的代码有什么问题。我检查了控制台,但什么都没有……

$('#stats li').each(function () {
    $(this).text().replace(/,/g, '.');
});

此代码应针对<ul id="stats"> 中的每个<li>。 然后它应该替换每个<li> 中的每个, 并用. 替换它

我也试过这个:

$('#stats li').each(function () {
        var comma = /,/g;
        if(comma.test($this)) {
            $(this).replace(comma, '.');
        }
});

我试过这个:

$('#stats li').each(function () {
    var stats = [];
    stats.push($(this).text());
    stats.replace(/,/g, '.');
    console.log(stats);
});

这里是Fiddle

【问题讨论】:

标签: javascript jquery


【解决方案1】:

问题是replace 方法返回一个新字符串。它不会就地修改字符串。试试这个:

$('#stats li').each(function () {
     $(this).text($(this).text().replace(/,/g, '.'));
});

但是,jQuery 的text 方法也接受一个函数。这是一个很多清洁工:

$('#stats li').text(function (index, text) { 
    return text.replace(/,/g, '.');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多