jquery中如何交换图片

发布于 2024-12-17 21:09:01 字数 263 浏览 4 评论 0原文

如何在单击图像时交换图像的 SRC 属性?

<a href="#">
    <img src="./layout/images/search.png" />
</a>

$('img[src="./layout/images/search.png"]').click(function () {
    $(this).attr('src',"./layout/images/search_select.png")
});

How can I swap an image's SRC attribute, on click of that image?

<a href="#">
    <img src="./layout/images/search.png" />
</a>

$('img[src="./layout/images/search.png"]').click(function () {
    $(this).attr('src',"./layout/images/search_select.png")
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱殇璃 2024-12-24 21:09:01

您可以尝试以下解决方案:

$("img").click(function(){
   $(this).attr("src","new.gif");
})

正如 David Hedlund 指出的那样,由于 img 选择器,这将更改页面上的所有图像。您可以按照 sam152 的建议使用类来定位图像,或者您可以使用它的 src 属性来定位图像 -

 $("img[src='old.gif']").click(function (){
   $(this).attr("src","new.gif");
})

请参阅我的演示 - JSFiddle

You can try this solution:

$("img").click(function(){
   $(this).attr("src","new.gif");
})

As David Hedlund points out this will change all images on a page due to the img selector. You could target an image using a class as sam152 suggests or, you could target an image using it's src attribute -

 $("img[src='old.gif']").click(function (){
   $(this).attr("src","new.gif");
})

See my demo - JSFiddle

绮烟 2024-12-24 21:09:01

如果您有一个名为“swap”的类的图像,则可以使用以下代码片段。它使用 click 事件,然后使用 attr 来更改图像 src 属性。

$('.swap').click(function(){ 
    $(this).attr('src','new/path/to/img.jpg');
});

If you have an image with a class called 'swap', you can use the following snippet. It uses the click event, and then attr, to change the images src attribute.

$('.swap').click(function(){ 
    $(this).attr('src','new/path/to/img.jpg');
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文