问题描述
Hi StackOverflow社区
Hi StackOverflow Community
我正在使用Django建立适合移动设备的网页.该页面包含一系列图像和一个按钮.当您单击按钮时,这些图像之一应被替换.
I am using Django to set up a mobile-friendly web-page. The page contains a series of images and a button. When you click the button one of those images should be replaced.
问题:我在HTML中使用了{%static'img/Test1.jpg'%}标签.仅在页面加载时才能正确呈现.
The problem:I use the {% static 'img/Test1.jpg' %} tag in the HTML. This is only rendered correctly when the page loads.
<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'%}.
I want to use jQuery to replace the first image, but the following code doesn't work as Django only renders the {% static 'img/Test2.jpg' %} on page-load.
$(document).ready( function() {
$("#about-btn").click( function(){
$('.chat_window img').attr("src","{% static 'img/Test2.jpg'%}");
});
});
是否有一种优雅的方法可以动态替换图像而不必向jQuery提供绝对路径?
Is there an elegant way to replace the image dynamically without having to provide jQuery with the absolute path?
任何建议将不胜感激!
Any advice would be highly appreciated!
谢谢M
推荐答案
Django不会在页面加载时不渲染模板. Django在页面加载之前渲染它.
Django does not render template on page-load. Django renders it before page-load.
如果您已经知道要粘贴的路径,则不需要Django静态标记:
If you already know what path you want to paste, then no need for Django static tag:
$("#about-btn").click( function(){
$('.chat_window img').attr("src","img/Test2.jpg");
});
这篇关于用jQuery替换Django中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!