繁体   English   中英

如何在 javascript 中获取 django 模板的 {{variable}} 的值?

[英]How to get the value of a {{variable}} of django template in javascript?

我现在从views.py中获取img 的值,我希望当用户单击图像时,它应该以模式打开。

  1. index.html图像部分:
<!-- Card body -->
<div class="card-body">
   {% for val in data.list %}
   <img src="{{val.Img}}" class="img-thumbnail pop_img">   -------here i'm getting the image properly and the path is showing correctly
   {% endfor %}
</div>

  1. index.html模态部分
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <img src="" class="imagepreview" style="width: 100%;" >
      </div>
    </div>
  </div>
</div>
  1. main.js
$(function() {
        $('.pop_img').on('click', function() {
            var img = $(this).find('img').attr('src')
            console.log(img)         -----------------but on console it prints : undefined 
            $('.imagepreview').attr('src', $(this).find('img').attr('src'));
            $('#imagemodal').modal('show');
        });
});

在检查元素时,它会在模态中显示<img src(unknown)>

如何获取 src attr 值并将其放置在模态上?

该行的.find() function 返回 class 中的所有 img 元素, var img = $(this).find('img').attr('src') 这个问题可以通过使用 .first() 来解决。 所以var img = $(this).first('img').attr('src')

暂无
暂无

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

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