我一直在尝试创建一种效果,即用户点击图片时,该图片会被另一张图片取代,该图片也充当链接。
但是我的问题是,每当我单击替换的图像时,链接都不起作用。
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
属性。您需要将图像包裹在 anchor 中并将 url 分配给它,或者进行自定义重定向。
注意检查元素时的图像 html:
<img src="https://placekitten.com/g/200/300" id="1" class="btnClick" href="google.com"> <!-- not valid! -->
这是无效的,因为 imgs 不是 anchor !
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);
(我试图制作一个 fiddle ,但它不会保存,但这应该可以)
您需要将操作存储在函数中,以便在需要时可以恢复。第一个操作是更改源,然后更改事件以像链接一样重定向您。
关于javascript - 链接不适用于图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29392502/