简体   繁体   中英

Changing img src via JavaScript

I got this HTML image item:

<img class="profile-photo img-responsive img-circle" id="imagen_perfil_banner" src="{{ asset('admin/img/profile1.jpg') }}" >

Then I got the JS that changes the src attribute of the image like this:

document.getElementById("imagen_perfil_banner").src = info[13];

The info[13] variable has the next information:

{{ asset('admin/img/1.jpg') }}

When tha page loads, it just doesn't show the image that I send via JS, but when I put the image directly on the image src attribute, it loads just fine.

Please try this:

var image = document.getElementById("imagen_perfil_banner")
image.src=info[13];

You firstly have to save the image in a variable. I hope it helps. Good luck.

Looks like your are using Angular or some similar templating engine like handelbars.js maybe Laravel.

This should work as expected if info[13] is a valid image url:

document.getElementById("imagen_perfil_banner").src = info[13];

The call {{ asset('admin/img/1.jpg') }} is not yet a valid url. You first have to process this as mentioned in the comments above to get the absolute url path of the asset.

You can change an image on the client side like this:

https://jsfiddle.net/0e8u38oo/

Hope this helps :)

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