【问题标题】:Replace image on mouse click using jQuery and Django doesn't work使用 jQuery 替换鼠标点击图像和 Django 不起作用
【发布时间】:2020-12-27 18:36:26
【问题描述】:

我想在使用 jQuery 单击图像时替换它。这是我的代码。

HTML

{% load static %}
<div class="col-md-6 image">
    <img class="map" src="{% static 'home/map.png' %}" class="doctors">
</div>

jQuery

$(document).ready(function() {
    $('.map').click(function() {
        $(this).attr("src", "{% static 'home/map2.png' %}");
    });
})

我尝试了上面的代码,但没有成功。图片的位置和图片格式已经是正确的,但是当我点击图片时它只显示一张空白图片(与我们写入错误图片格式时的显示相同)。

我已经尝试过把 jQuery 改成这个了

$('.map').click(function() {
    $(this).attr("src", "home/map2.png");
});

但它仍然没有工作。谁知道怎么解决?

【问题讨论】:

标签: javascript html jquery django


【解决方案1】:

这是您在可运行堆栈-sn-p 中的解决方案。

$(document).ready(function() {
    $('.map').click(function() {
        var img2 = $(this).attr("data-img2");
        $(this).attr("src", img2);
    });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6 image">
       <img class="map" data-img2="https://homepages.cae.wisc.edu/~ece533/images/arctichare.png" src="https://homepages.cae.wisc.edu/~ece533/images/airplane.png"> 
</div>

【讨论】:

    【解决方案2】:

    使用类似的东西来避免 JS 错误以及流动代码


    HTML

    {% load static %}
    <div class="col-md-6 image">
        <img class="map" data-img2="{% static 'home/map2.png' %}" src="{% static 'home/map.png' %}" class="doctors">
    </div>
    

    jQuery

    $(document).ready(function() {
        $('.map').click(function() {
            var img2 = $(this).attr("data-img2");
            $(this).attr("src", img2 );
        });
    });
    

    【讨论】:

    • 感谢发布。我使用示例图像和一个可运行的 sn-p 来轻松直观地展示它的工作原理。
    猜你喜欢
    • 2014-05-03
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    相关资源
    最近更新 更多