简体   繁体   中英

Changing img tag src value using javascript with the Django framework

I am trying to load a random image from a dictionary on page load using Javascript. This is the HTML

  <div class="img-container">
    {% load static %}
    <img id="qimage" src="{% static '' %}"></img>
  </div>

So basically I want to change the src to a random generated image src from dictionary on page load: this is the Javascript:

window.onload = function(){ 
  var image = document.getElementById("qimage");
  let src = getRandomImage();
  image.setAttribute("src",src);
}

And this is the generate random image function:

function getRandomImage(){
 var keys = Object.keys(dict);
 var index = getRandomInt(0,keys.length);
 var selection = keys[index];
 var image = dict[selection][0];
 return image;
}

and lastly this is the dictionary:

var dict = {
 "barrackStreet":["{% static 'images/hard/bstreet.jpg' %}",{"lat":51.893897,"lng":-8.477632}],
 "GrandParade":["{% static 'images/hard/gparade.jpg' %}",{"lat":51.893897,"lng":-8.477632}],
 "PatricksHill":["{% static 'images/hard/phill.jpg' %}",{"lat":51.893897,"lng":-8.477632}],
};

Why don't you move that logic to Python/Django? In that way you won't need to write JS code. Note this will only work if your dict variable has a fixed value and not randomly generated from JS side.

You can use Django's a built-in filter random to randomly choose a value from a list. Make a list containing your image directories like this:

dict = {
 "barrackStreet":["{% static 'images/hard/bstreet.jpg' %}",{"lat":51.893897,"lng":-8.477632}],
 "GrandParade":["{% static 'images/hard/gparade.jpg' %}",{"lat":51.893897,"lng":-8.477632}],
 "PatricksHill":["{% static 'images/hard/phill.jpg' %}",{"lat":51.893897,"lng":-8.477632}],
}
img_list = [v[0] for k,v in dict.items()]

Then pass that from your view to your template and in your template render it like this:

<img id="qimage" src="{{ img_list|random }}"></img>

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