繁体   English   中英

使用 jQuery 将 CSS 添加到带有 alt 标签的特定图像

[英]Add CSS to specific image with alt tag using jQuery

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

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>

希望这是有道理的?

您不一定需要 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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM