javascript - 使用 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>
希望这有意义吗?
解决方案
您不一定需要 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");
推荐阅读
- jquery - 如果已在另一个下拉列表中选择了该值,如何删除下拉列表中的值
- java - 如何通过 API Spring Boot 获取特定字段
- python - 计算不同数据框中两个列表之间的匹配python
- android - 我们如何为回收器视图的每个列表项(每一行)设置 onClickListener,为不同的列表对象设置不同的活动
- android - 使用 API 16 和 17 向集合添加值时出现 Firestore 错误
- php - 如何在modal中从mysql中获取对应的id数据?
- javascript - React:如何从外部函数更新我的组件状态?
- mysql - 返回mysql连接的函数
- mocking - 如何验证链式方法调用?
- html - 无法更改 PWA Vuex 项目中的网站图标