【问题标题】:Django cloudinary image how to add onClick event in template {% %} tag?Django cloudinary 图像如何在模板 {% %} 标签中添加 onClick 事件?
【发布时间】:2021-11-27 20:32:04
【问题描述】:

我正在成功创建 Cloudinary 图像,如下所示:

{% cloudinary photo.filename 
    width='300' 
    crop='fill' 
    class='item_photo' 
    id=photo.filename %}

这会导致 html img 标签:

<img 
    class="item_photo" 
    id="xxxxxx"         
    width="300"
    src="https://res.cloudinary.com/xxx/image/upload/c_fill,w_300/vxxx/xxx.jpg">

但是,我想向 img 添加一个 onClick 事件,但无法找出正确的语法,或者即使有可能。

我希望 html 标记看起来像:

<img 
    class="item_photo" 
    id="xxxxxx"         
    width="300"
    onClick=imageClick('xxxxxx')  <=== event variable is same as `id` value
    src="https://res.cloudinary.com/xxx/image/upload/c_fill,w_300/vxxx/xxx.jpg">

idimageClick 变量本身由 Django 模板标记值 photo.filename 填充。

我尝试过的一些事情:

onClick='photoClick(photo.filename)' %}

{% with add:'onClick=photoClick('{{ photo.filename }}|add:') as onclick %}{{ onclick }}{% endwith %}

|add:'onClick=photoClick('{{ photo.filename }}|add:')' %}

如何构造此模板标签的onClick=photoClick(xxx) 部分?

【问题讨论】:

    标签: django cloudinary


    【解决方案1】:

    您可以将 onClick 属性添加到 img 标记中,如下所示(例如 photo.filename=sample_image):

    {% cloudinary photo.filename width="300" crop="fill" class="item_photo" id=photo.filename onclick="photoClick(this)" %}
    

    添加脚本函数photoClick(),可以接受img标签对象,可以处理为:

    <script type="text/javascript">
        function photoClick(img) {
            
            console.log("The src data is: " + img.src);
            console.log("The id data is: " + img.id);
            
            var filename = img.src.substring(img.src.lastIndexOf('/')+1);
            console.log("The filename is: " + filename);
            
            // Other actions
            var src = img.src;
            window.open(src);
        }
    </script>
    

    生成的 HTML 标记将是:

    <img class="item_photo" id="sample_image" onclick="photoClick(this)" src="https://<your_cloudinary_image_url_path>/sample_image.<ext>" width="300"/>
    

    【讨论】:

      猜你喜欢
      • 2016-01-13
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2018-08-14
      • 1970-01-01
      • 2020-01-25
      • 2012-02-10
      相关资源
      最近更新 更多