用 jQuery 替换元素内文本的条件语句

Conditional statement for replacing text inside of an element with jQuery

在某些 span 元素内生成了文本,如果满足正确的条件,我想替换其中的文本。我想要换出的文本是 "am"(意图切换到 a.m。)或 "pm"(切换到 p.m),条件基本上是“如果此范围包含带有 'am' 或 'pm' 的字符串的一部分,用 'a.m.' 或 'p.m.'.

替换该字符串的一部分

我的 html/php 看起来像这样...

<span id="start-time">
  ~Drupal Jargon which essentially outputs something like:~
  5 pm
</span>

我可以用 text().replace 替换这个例子中的 pm...

$("#start-time").each(function() {
  $am = $(this).text().replace('pm','p.m.');
  $(this).text($am);
});

... 但是我创建的条件语句(如下所示)从开始时间跨度内的文本字符串中删除了“5”,因此它只输出 "p.m.",而不是所需的“5 p.m...

$("#start-time").each(function() {
  if ($("#start-time").text("pm")) {
    $pm = $(this).text().replace('pm','p.m.');
    $(this).text($pm);
  }
});

如何修正我的代码,使条件语句输出所需的文本?

由于您正在使用 "each"(查看文档,http://api.jquery.com/jquery.each/),您应该使用回调参数。 不是

$(".start-time").each(function() {
  if ($("#start-time")..

但是

$(".start-time").each(function(i,e) {
  if ($(e)..

演示在这里 https://jsfiddle.net/uet5LbLb/