首页 > 解决方案 > 使用 jQuery 将 CSS 添加到带有 alt 标签的特定图像

问题描述

我正在尝试在图像 alt 标记中搜索特定文本并使用 jQuery 将 CSS 添加到该图像。我正在使用:contains来自 jQuery,但我不确定这是否是最好的方法?到目前为止,这是我正在尝试的:

jQuery

var imgAlt = $("img").attr("alt");

$("imgAlt:contains('morning hike')").css("border", "5px solid black");

HTML:

<div>
  <img src="https://images.unsplash.com/photo-1584879788725-56a4b394de8d?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ" alt="candles on table">
  <img src="https://images.unsplash.com/photo-1584354012731-ba34cef5963f?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ" alt="morning hike">
</div>

希望这有意义吗?

标签: javascriptjqueryhtmlcss

解决方案


您不一定需要 javascript,可以仅使用 css 属性选择器创建选择器:https ://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

img[alt*='morning hike'] { border: 5px solid #000 }

我们可以在您的 jQuery 中使用相同的选择器

$("img[alt*='morning hike']").css("border", "5px solid black");


推荐阅读