简体   繁体   English

如何在Django模板中使用javascript变量获取数组元素?

[英]how to get an array element with javascript variable in django template?

i`m creating a slider so i want to get an element of template array in Django. 我正在创建一个滑块,所以我想在Django中获取模板数组的元素。 my HTML file is: 我的HTML文件是:

<div id="sideBar_mostVisited_control">
    <a href="">
        <p>
            {{ mostVisited_names.0 }}
        </p>
    </a>
    <div>
        <p>
            1
        </p>
    </div>
    <button type="button" id="mostVisited_arrowRight">
        <img src="{% static 'icons/base/arrowRight.png' %}" id="mostVisited_arrowRight">
    </button>
    <button type="button" id="mostVisited_arrowLeft">
        <img src="{% static 'icons/base/arrowLeft.png' %}" id="mostVisited_arrowLeft">
    </button>
</div>
<div id="sideBar_mostVisited_images">
    <div>
        {% for image in mostVisited_images %}
            <img src="{{ image }}">
        {% endfor %}
    </div>
</div>

i want to change name when its image changed. 我想在其图像更改时更改名称。 my jQuery file is: 我的jQuery文件是:

var index=$('#sideBar_mostVisited_control div p').html();
$('#sideBar_mostVisited_control div p').html(index+1);
$('#sideBar_mostVisited_control a p').html("{{ mostVisited_names.index }}");

but index is not recognized in {{ mostVisited_names.index }} . {{ mostVisited_names.index }}无法识别索引。 what can i do? 我能做什么?

The problem : 问题 :

Since the JS file is static, you can't put Django variables into it. 由于JS文件是静态文件,因此无法将Django变量放入其中。

A solution : 一个解法 :

A way to resolve this situation is to "store" Django variables needed for your js in your html. 解决这种情况的一种方法是将js所需的Django变量“存储”在html中。 Afterward you can grab it and use it in your js script ! 之后,您可以抓住它并在您的js脚本中使用它!

Some code : 一些代码:

<script type="text/javascript">
  // "store" variables from Django in the body
  $('body').data('name_index', {{mostVisited_names.index}});
</script>

Then in your JS, get the value from the datamap: 然后在您的JS中,从数据映射中获取值:

var index=$('#sideBar_mostVisited_control div p').html();
$('#sideBar_mostVisited_control div p').html(index+1);
$('#sideBar_mostVisited_control a p').html($('body').data('name_index'));

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

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