【问题标题】:How to get the value of a {{variable}} of django template in javascript?如何在javascript中获取django模板的{{variable}}的值?
【发布时间】:2020-11-12 07:17:45
【问题描述】:

我现在从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');
        });
});

在检查元素时,它会在模态框内显示&lt;img src(unknown)&gt;

如何获取 src attr 值的值并将其放在 modal 上?

【问题讨论】:

    标签: javascript html python-3.x django django-templates


    【解决方案1】:

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

    【讨论】:

    • 它是如何获取我点击的图像的 src 的。我认为它会在所有 img 标签之间选择第一个 src。我想如果我有 10 个 src,它每次都会选择第一个,但事实并非如此。为什么要选择当前的 src,点击了哪个图像?它醒来很好。很好,感谢您的帮助
    猜你喜欢
    • 2011-03-21
    • 2011-11-22
    • 1970-01-01
    • 2013-07-23
    • 2018-09-23
    • 2016-05-30
    • 2023-03-31
    • 2011-11-03
    • 1970-01-01
    相关资源
    最近更新 更多