scripts.js 代码:
$(document).ready(function(){
$('#user').hover(function() {
$('#user img').attr('src', "{% static 'images/user_selected.png' %}");
}, function() {
$('#user img').attr('src', "{% static 'images/user.png' %}");
});
});
当我直接将其写入 base.html 文件时,它工作正常,但是当我将其放入外部 .js 文件时,它无法加载图像。
Scripts.js 文件加载,但图像不加载。
base.html代码:
<head>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="{% static 'js/scripts.js' %}"></script>
...
</head>
<body>
...
<a href="{%url 'logout' %}">LOG OUT</a>
<a id="user" href="#">
<img src="{% static 'images/user.png' %}" />
<span id="user-name">{{request.user.username}}</span>
</a>
...
</body>
最佳答案
问题是因为您使用的模板语法(即 {% static 'images/user_selected.png' %}
)不会在 JS 文件中解释。
要解决此问题,您可以将图像源放在 HTML 中 img
的 data
属性中,然后可以在外部 JS 中读取,如下所示:
jQuery($ => {
$('#user').hover(function() {
$(this).children('img').prop('src', function() {
return $(this).data('over');
});
}, function() {
$(this).children('img').prop('src', function() {
return $(this).data('leave');
});
});
});
<a id="user" href="#">
<img src="{% static 'images/user.png' %}" data-over="{% static 'images/user_selected.png' %}" data-leave="{% static 'images/user.png' %}" height="14px" width="14px" id="user-icon" />
<span id="user-name">{{request.user.username}}</span>
</a>
关于jquery - 从 .js 文件中的静态加载图像时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60639595/