find if a img have alt in jquery if not then add from array

前端 未结 3 1179
挽巷
挽巷 2021-01-29 04:54

first need to find all img in the sites

$(\"#body\").find(img)

and then check if the img have the \"alt\" attribute, if image have the attribut

相关标签:
3条回答
  • 2021-01-29 05:39

    You can do it all with one selector:

    $("#body img[alt!='']").each(function(){
        // What you want here...
    });
    

    Or this:

    $("#body img[alt!=''][alt]").each(function(){
    

    depends on the DOM structure.

    Or with a filter function:

    $("#body img").filter(function(){
        return this.alt;
    }).each(function(){
        // What you want here...
    });
    

    If you want to do it all with one each, you can use this:

    $("#body img").each(function(){
        if (this.alt)
            // Do something.
        else
            // Do something else.
    });
    
    0 讨论(0)
  • 2021-01-29 05:42
    var arr = ['hello', 'hi', 'yo'];
    $('#body img').each(function() {
        if ( ! $(this).attr('alt'))
            $(this).attr('alt', arr[Math.round(Math.random() * (arr.length - 1)))]);
    });
    
    0 讨论(0)
  • 2021-01-29 05:46

    This should help get you started:

    $("#body img").each(function(){
       var $this = $(this);
       if (!$this.attr("alt")){
         //do something
       }
    });
    
    0 讨论(0)
提交回复
热议问题