简体   繁体   中英

Add alt atttibute to an image in javascript

I need some help and guidence. Can someone help me add the alt attribute of an image in this code? I've tried this: slide.prepend($(imgLoaded).attr('class','imgLoaded','alt','Image').css('visibility','hidden')); but didn't work. Any ideas? Thank you

var slide = $('.cameraSlide:eq('+slideI+')',target);
    var slideNext = $('.cameraSlide:eq('+(slideI+1)+')',target).addClass('cameranext');
    if( vis != slideI+1 ) {
        slideNext.hide();
    }
    $('.cameraContent',fakeHover).fadeOut(600);
    $('.camera_caption',fakeHover).show();
    
    $('.camerarelative',slide).append($('> div ',elem).eq(slideI).find('> div.camera_effected'));

    $('.camera_target_content .cameraContent:eq('+slideI+')',wrap).append($('> div ',elem).eq(slideI).find('> div'));
    
    if(!$('.imgLoaded',slide).length){
        var imgUrl = allImg[slideI];
        var imgLoaded = new Image();
        imgLoaded.src = imgUrl +"?"+ new Date().getTime();
        slide.css('visibility','hidden');
        slide.prepend($(imgLoaded).attr('class','imgLoaded').css('visibility','hidden'));
        var wT, hT;
        if (!$(imgLoaded).get(0).complete || wT == '0' || hT == '0' || typeof wT === 'undefined' || wT === false || typeof hT === 'undefined' || hT === false) {
            $('.camera_loader',wrap).delay(500).fadeIn(400);
            imgLoaded.onload = function() {
                wT = imgLoaded.naturalWidth;
                hT = imgLoaded.naturalHeight;
                $(imgLoaded).attr('data-alignment',allAlign[slideI]).attr('data-portrait',allPor[slideI]);
                $(imgLoaded).attr('width',wT);
                $(imgLoaded).attr('height',hT);
                target.find('.cameraSlide_'+slideI).hide().css('visibility','visible');
                resizeImage();
                nextSlide(slideI+1);
            };
        }
    }

When setting attribute values, the attr method takes two arguments.

attr(name, value)

You are passing it four arguments ( attr(name, value, secondName, secondValue) ) which is wrong.

If you want to set two attributes, call it twice.

Wrap it with an object.

$(imgLoaded).attr({
    'class':'imgLoaded',
    alt:'Image'
}).css('visibility','hidden');

Ref: https://api.jquery.com/attr/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM