链接无法处理图像

Link not working on image?

本文关键字:图像 处理 链接      更新时间:2023-09-26

我一直在尝试创建一个效果,用户点击一个图像,该图像被另一个图像取代,该图像也充当链接。

然而,我的问题是,每当我点击被替换的图像时,链接都不起作用。

Fiddle:http://jsfiddle.net/ha6qp7w4/321/

$('.btnClick').on('click',function(){
    $(this).attr('src','https://placekitten.com/g/200/300')
    $(this).attr('href','google.com')
});

img标记没有href属性。您需要将图像包装在锚点中,并将url分配给该锚点,或者进行自定义重定向。

注意你的图像html元素检查:

<img src="https://placekitten.com/g/200/300" id="1" class="btnClick" href="google.com"> <!-- not valid! -->

这是无效的,因为img不是锚点!

function first() {
    this.src = 'https://placekitten.com/g/200/300';
    $(this).unbind("click");
    $(this).on("click", second);
}
function second() {
    window.location.href = "https://www.google.com";
    $(this).unbind("click");
    $(this).on("click", first);
}
$('.btnClick').on('click', first);

(我试着做一把小提琴,但它救不了,但这应该有效)

你需要将你的操作存储在函数中,这样你就可以在需要时恢复。第一个操作是更改源,然后更改事件以像链接一样重定向你。

这里有一个例子。

示例

html部分

<img src="http://i.imgur.com/o46X87d.png" data-new="http://i.imgur.com/9lf2Mjk.png" id="1" class="btnClick" />

使用图像的新url在图像上添加数据新属性并将其替换为js

$('.btnClick').on('click',function(){
    var url = $(this).attr("data-new");
    $(this).attr("src", url);
});

我会使用一种完全不同的方法,但以下是如何使用现有代码来做到这一点:

<div class="btnClick">
<img src="http://i.imgur.com/o46X87d.png" id="1" />
<a href="javascript:check()" id="2" style="display:none;">
    <img src="http://i.imgur.com/9lf2Mjk.png" id="static" />
</a>
</div>
<script type="text/javascript">
$('.btnClick').on('click',function(){
    if($('#1').is(':visible')) {
        $('#1').hide();
        $('#2').show();
    } else {
        $('#1').show();
        $('#2').hide();
    }
});
</script>

我故意不使用toggle()来更好地展示这项技术,以防你想在点击图像出现时关闭点击事件。