jquery - 从 .js 文件中的静态加载图像时出现问题

标签 jquery django

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 中 imgdata 属性中,然后可以在外部 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/

相关文章:

javascript - Owl Carousel 2 - 隐藏自定义导航(如果有 1 项)

javascript - 禁用 jQuery 函数

javascript - Fullcalendar 获取位置或获取资源

python - Django 中的计数字段?

python - Django `manage.py test` 忽略了一些测试

python - 修改中间件中的 Django 设置变量

javascript - 使用 post 方法提交表单后,为什么在 php 中表单数据附加到 url?

Django modelForm 未将文件保存到数据库

python - object() 不带参数

javascript - 如何在 jQuery 中更改选择时传递 php 数组?