简体   繁体   中英

change img src using jquery

<div class="s4-titlelogo">
 <a href="/sites/mysite">
<img name="onetidHeadbnnr0" id="ctl00_onetidHeadbnnr2" style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px;" alt="bobpub" src="/_layouts/images/blank.gif" complete="complete"/>
</a>
</div>

If the src attribute of the img is blank.gif, then i want to set the src attribute to my icon url "/_layouts/images/myicon.gif". I need to reference the img as this $('.s4-titlelogo img').

SO FAR:

iconurl = $('.s4-titlelogo a>img').attr("src");
            if (iconurl == ""/_layouts/images/blank.gif")
            {

            }

If the src attribute of the img is blank.gif...

if($('.s4-titlelogo img').attr('src') === '/_layouts/images/blank.gif')

...then i want to set the src attribute to my icon url.

$('.s4-titlelogo img').attr('src', '/_layouts/images/myicon.gif');

Edit: Three downvotes instantly? Uh... why?

Here's a JSFiddle example to prove that this works.

Just do this...

Live demo: http://jsfiddle.net/oscarj24/FW4kj/

$(function(){

    //Get the element
    elem = $('.s4-titlelogo img');

    //If 'src' attribute contains 'blank.gif'
    if (elem.prop('src').indexOf('blank.gif') > 0)
        //Replace 'src' attribute with 'myicon.gif'
        elem.prop('src', '/_layouts/images/myicon.gif');

    //Alert new 'src' attribute just to verify
    alert('New image url is: ' + elem.prop('src'));

});

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