【问题标题】:Change all divs content if contains a specific word and a number greater than 1如果包含特定单词和大于 1 的数字,则更改所有 div 内容
【发布时间】:2023-01-22 11:12:38
【问题描述】:

晚上好!

我有很多带有“.goods__variants”类和内部不同文本的div。 因此,如果我有“1 种颜色”,它是正确的,但如果我有 15 种颜色,我会看到“15 种颜色”,所以不正确。我需要更改所有包含内部数字大于 1 的 div,并将文本“颜色”替换为“颜色”。

我会尝试这样做,但我不想为每个数字写下每一行值。如何为所有数字更动态地完成此操作?非常感谢!

代码:

$('.goods__variants').each(function() {
   var text = $(this).text();
   text.indexOf("4 Farbe") >= 0 ? text = text.replace('4 Color', '4 Colors') : null;
   $(this).text(text);
});

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    判断是否需要复数,只需要判断单数1是否存在即可。如果没有,则将color 更改为colors

    $('.goods__variants').each(function() {
      const original = $(this).text();
      if (!/1/.test(original)) {
        $(this).text(original.replace(/color/, 'colors'));
      } // add an else here if you want to change colors back to color
    });
    

    1 将 1 包围在单词边界内,以便仅匹配独立编号 1

    color 用单词边界包围 color,这样只有独立的单词 color 被匹配(而不是,例如,colors 中的 color)。

    【讨论】:

    • 非常感谢您的完整回答,效果很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 2014-10-27
    • 2017-09-20
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    相关资源
    最近更新 更多