我有很多.png图片,想要在提供替代文字的地方得到一个提及的名称,如果alt标签中未提及,则应该显示’png-image’.
下面的代码只是将所有png图像的替代文本“ png-image”放入.
假设我有一个图像的替代文本,即alt =“ facebook”,它应该显示alt =“ facebook”代替alt =“ png-image”.
通过查看源代码,它显示alt =“ facebook”代替alt =“ png-image”
@H_404_12@<script type="text/javascript"> (function ($) { $(document).ready(function() { // apply Image alt attribute $('img[src$=".png"]').attr('alt','png-image'); }); }(jQuery)); </script>
最佳答案
您可以使用.each方法在其src末尾使用.png循环遍历所有图像.然后,可以在每个图像上使用以下命令检查它是否具有alt属性:
@H_404_12@if(!$(this).attr('alt'))
如果图像当前没有alt,则该if语句将运行,因此您可以向图像添加自己的alt属性.
请参见下面的工作示例:
@H_404_12@$(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 }) })
@H_404_12@<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" />