[英]How to change alt text of image who has empty alt text
I have a div inside whose chile tehre can be number of images What i want's to do is if there is any img with alt="" i want's to change it to alt="category" How can i do it with jquery. 我有一个div,里面的智利辣椒可以是图像数量。我要做的是,是否有带有alt =“”的img,我想将其更改为alt =“ category”,如何用jquery做到这一点。 Currently ia m able to get all the img elements and trying to check there value first [so that if there is a alt have value i will not touch it] but unsuccessful My current code is
目前,我能够获取所有img元素,并尝试首先检查其中的值[因此,如果有alt,则我不会碰它。]但不成功,我当前的代码是
var label = $("#viewCategoriesForBlog").find('img').attr('alt');
for(var i=0;i<label.length;i++){
alert( label[i].value);
}
var label = $("#viewCategoriesForBlog").find('img').attr('alt');
// label will hold only the first alt value
It has to be like 它必须像
var label = $("#viewCategoriesForBlog").find('img');
for(var i=0;i<label.length;i++){
alert( $(label[i]).attr('alt'));
}
此操作将解决您的最初问题:
$('#viewCategoriesForBlog img[alt=""]').attr('alt', 'category');
Like this: 像这样:
$("#viewCategoriesForBlog img[alt=''], #viewCategoriesForBlog img:not([alt])")
.attr("alt", "Category");
Selectors explained: 选择器说明:
#viewCategoriesForBlog img[alt=""]
returns img tags that have alt=""
#viewCategoriesForBlog img[alt=""]
返回具有alt=""
img标签 #viewCategoriesForBlog img:not([alt])
returns img tags that do not have alt
attribute #viewCategoriesForBlog img:not([alt])
返回不具有alt
属性的img标签 You need to loop over the elements in the selector. 您需要遍历选择器中的元素。 You cannot loop over attributes of the elements in a selector.
您不能在选择器中循环显示元素的属性。 Try this:
尝试这个:
$("#viewCategoriesForBlog img").each(function(i, el) {
alert($(el).prop('alt'));
});
try something like this 尝试这样的事情
$("#viewCategoriesForBlog").find('img').each(function(){
if(this.alt.trim() == ''){
this.alt = 'category';
}
})
This fiddle alerts all the empty alt tags: http://jsfiddle.net/4ZnJN/1/ 这个小提琴警告所有空的alt标签: http : //jsfiddle.net/4ZnJN/1/
$("img").each(function(){
var label = $(this).attr('alt');
if(label.length < 1){
alert(label);
}
});
Might want to shrink it down to your specific structure in stead of all img tags 可能希望将其缩小为您的特定结构,而不是所有img标签
I'm aware that's absolutely not accessible, but here I only needed to avoid WCAG validator to highlight images with no alternative text. 我知道这绝对是不可访问的,但是在这里,我只需要避免WCAG验证器突出显示没有替代文本的图像。
var images = document.querySelectorAll('img');
if(images) {
for (var i = images.length - 1; i >= 0; i--) {
var alt = images[i].getAttribute('alt');
if(!alt){
images[i].setAttribute('alt', 'no alt text');
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.