我有许多图像,并想得到一个提到的名字,在那里提供了替代文本,如果没有在alt标签中提到,它应该显示‘png- .png’。
下面的代码只是将所有png图像的替代文本放入'png-image‘。
假设我有一个图像的alt文本,即alt="facebook",它应该显示alt="facebook"而不是alt="png-image"。
通过查看源代码,它正在显示alt="facebook"而不是alt="png-image"
<script type="text/javascript">
(function ($) {
$(document).ready(function() {
// apply Image alt attribute
$('img[src$=".png"]').attr('alt', 'png-image');
});
}(jQuery));
</script>发布于 2019-02-13 16:30:06
您可以在.png的src末尾使用.each方法循环遍历所有图像。在每个图像中,您可以使用以下命令检查它是否具有alt属性:
if(!$(this).attr('alt'))如果映像当前没有alt,则将运行此if语句,因此您可以将自己的alt属性添加到映像。
请参见下面的工作示例:
$(document).ready(function() {
$('img[src$=".png"]').each(function() {
if (!$(this).attr('alt')) // check if current image tag has alt attribute
$(this).attr('alt', 'png-image'); // if it doesn't add 'png-image' alt attribute
})
})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="foo.png" /><br />
<img src="bar.png" alt="this is my own alt" /><br />
<img src="foo2.png" alt="this is my own alt2" /><br />
<img src="foo.png" />
这将适用于alt属性未设置或设置为空(即:alt="")的两种情况
发布于 2019-02-13 16:35:50
您可以使用当前选择器添加[alt=""]选择器
(function($) {
$(document).ready(function() {
// apply Image alt attribute
$('img[src$=".png"][alt=""]').attr('alt', 'png-image');
});
}(jQuery));<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src='https://images.pexels.com/photos/599708/pexels-photo-599708.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500' alt='image'>
<img src='https://fnetobits.s3.amazonaws.com/galleries/boyerfuneralhome/1819974/1138985594.png' alt=''>
发布于 2019-02-13 16:36:43
您可以使用JQuery中的基于属性的选择器来获取所有没有alt属性的img标签。
$(document).ready(function() {
$('img[src$=".png"][alt='']').attr('alt','png-image');
})https://stackoverflow.com/questions/54665545
复制相似问题