【问题标题】:Replacing images in Django with jQuery用 jQuery 替换 Django 中的图像
【发布时间】:2016-04-10 04:20:52
【问题描述】:

你好 StackOverflow 社区

我正在使用 Django 设置一个适合移动设备的网页。该页面包含一系列图像和一个按钮。当您单击按钮时,应替换这些图像之一。

问题: 我在 HTML 中使用 {% static 'img/Test1.jpg' %} 标签。这仅在页面加载时正确呈现。

<div class="container" id="top_container">
    <div class="row"> <!-- Major Row containing both the chat window and the autoring window -->
        <div class="col-lg-4 center-block">
            <h1>{{secretDisplay.secretTitle}}</h1>
                <div class="row">
                    <div class="col-ls-12 center-block" id="child"> <!-- Chat Window -->
                        <p contenteditable="true" class="chat_window" style="text-align:left">
                            <img src="{% static 'img/Test1.jpg'%}" class="icon_one"/><img src="{% static 'img/Test1.jpg'%}" class="icon_one"/><img src="{% static 'img/Test1.jpg'%}" class="icon_one"/><img src="{% static 'img/Test1.jpg'%}" class="icon_one"/><img src="{% static 'img/Test1.jpg'%}" class="icon_one"/><img src="{% static 'img/Test1.jpg'%}" class="icon_one"/><img src="{% static 'img/Test1.jpg'%}" class="icon_one"/><img src="{% static 'img/Test1.jpg'%}" class="icon_one"/><img src="{% static 'img/Test1.jpg'%}" class="icon_one"/><img src="{% static 'img/Test1.jpg'%}" class="icon_one"/>
                        </p>
                    </div>
                </div>
                <div> <!-- This is where we will author the messages -->
                    <p contenteditable="true" class="col-ls-12 center-block write_window author_box">This is the test</p>
                </div>
        </div>
     </div>
</div>

我想用 jQuery 替换第一张图片,但是下面的代码不起作用,因为 Django 只在页面加载时呈现 {% static 'img/Test2.jpg' %}。

$(document).ready( function() {
    $("#about-btn").click( function(){
        $('.chat_window img').attr("src","{% static 'img/Test2.jpg'%}");
    });
});

有没有一种优雅的方式来动态替换图像而不必为 jQuery 提供绝对路径?

任何建议将不胜感激!

谢谢 M

【问题讨论】:

  • 您有针对该问题的fiddle 吗?会有帮助的。
  • 这里是link,但我不确定这有什么帮助,因为小提琴无法呈现 django 标签,我认为这可能是这里的问题。
  • 嗨@saravanann。感谢您的评论。不幸的是,这并不能解决我的问题,因为标签仍然在页面加载之前/页面加载时呈现一次。我的目标是在页面加载后动态替换和显示图像。

标签: javascript jquery html django


【解决方案1】:

Django 仅在页面加载时呈现 {% static 'img/Test2.jpg' %}。

Django 在页面加载时渲染模板。 Django 在页面加载之前渲染它。

如果你已经知道要粘贴的路径,那么不需要 Django 静态标签:

$("#about-btn").click( function(){
    $('.chat_window img').attr("src","img/Test2.jpg");
});

【讨论】:

  • 嗨@donjiyor。感谢您的建议。我考虑了这一点,但想知道是否有更优雅的解决方案可以让我继续使用与绝对路径相反的 Django 标签。原因是我可能需要稍后根据用户输入动态更改路径。
猜你喜欢
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 2014-10-09
  • 2013-09-19
  • 1970-01-01
  • 2018-08-26
  • 2023-03-13
  • 1970-01-01
相关资源
最近更新 更多