如果没有,则查找img是否在jquery中有alt,然后从数组中添加
首先需要在网站中找到所有img
$("#body").find(img)
然后检查img是否具有“alt”属性,如果图像具有将被转义的属性,并且如果它没有或者alt为空,则将从列表或数组中随机地将字符串添加到img。
我现在必须使用.each()一些函数,但我是jquery的新手,所以有点帮助是完美的。
var arr = ['hello', 'hi', 'yo']; $('#body img').each(function() { if ( ! $(this).attr('alt')) $(this).attr('alt', arr[Math.round(Math.random() * (arr.length - 1)))]); });
您可以使用一个选择器完成所有操作:
$("#body img[alt!='']").each(function(){ // What you want here... });
或这个:
$("#body img[alt!=''][alt]").each(function(){
取决于DOM结构。
或者使用filter
function:
$("#body img").filter(function(){ return this.alt; }).each(function(){ // What you want here... });
如果你想一个人做一个,你可以使用这个:
$("#body img").each(function(){ if (this.alt) // Do something. else // Do something else. });
这应该有助于您入门:
$("#body img").each(function(){ var $this = $(this); if (!$this.attr("alt")){ //do something } });