简体   繁体   English

使用 javascript 和 Django 框架更改 img 标签 src 值

[英]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我正在尝试使用 Javascript 在页面加载时从字典中加载随机图像。这是 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:所以基本上我想在页面加载时将 src 更改为从字典中随机生成的图像 src:这是 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:

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?为什么不将该逻辑移至 Python/Django? In that way you won't need to write JS code.这样你就不需要编写 JS 代码了。 Note this will only work if your dict variable has a fixed value and not randomly generated from JS side.请注意,这仅在您的dict变量具有固定值并且不是从 JS 端随机生成时才有效。

You can use Django's a built-in filter random to randomly choose a value from a list.您可以使用 Django 的内置过滤器random从列表中随机选择一个值。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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