【问题标题】:else condition is not working for src attribute in jquery [duplicate]else 条件不适用于 jquery 中的 src 属性 [重复]
【发布时间】:2018-09-05 17:21:22
【问题描述】:

一直在尝试使用以下代码在网页中添加替代文本 能够获得第一张图像的正确值,但如果和其他条件除外 无法正常工作。无法为其他图片添加替代文字

$(document).ready(function() {

  $("img ").each(function() {
    var img = $(this);

    if (!img.attr("alt") || img.attr("src") === "/temp/iconcache/flags/32x32/flag_brazil.png")
      img.attr("alt", "Brazil Flag");
    else if (!img.attr("alt") || img.attr("src") === "/temp/iconcache/flags/32x32/flag_China.png")
      img.attr("alt", "China Flag");
    else {
      img.attr("alt", "");
    }
  });
});

【问题讨论】:

  • 给你:$("img").each(function() { var img = $(this); if (!img.attr("alt") && img.attr("src") === "/temp/iconcache/flags/32x32/flag_brazil.png") img.attr("alt", "Brazil Flag"); else if (!img.attr("alt") && img.attr("src") === "/temp/iconcache/flags/32x32/flag_China.png") img.attr("alt", "China Flag"); else { img.attr("alt", ""); } }); 你也可以使用indexOf 来检查 src 是否包含文本。例如:if(!img.attr("alt") && img.attr("src").indexOf("flag_brazil.png") !== -1)
  • 感谢您的解决方案,这对我有用。

标签: javascript jquery if-statement src


【解决方案1】:

当您需要&& 时,您正在使用||。您的每个条件都有if (!img.attr("alt") || ...,这意味着如果图像的alt 属性为空,则条件表达式的其余部分将被忽略。这意味着空的alt 将导致第一个分支(“巴西”)运行,而不管src 属性的值如何。

【讨论】:

  • 您还可以在其他 if 之前添加一个 if (!img.attr('alt')) return; 以短路其余代码。这样您就不必重复检查。
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 2013-04-16
  • 2021-07-18
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 2015-06-13
  • 2014-09-14
相关资源
最近更新 更多