我有一堆带有图标的链接。 单击链接时,与其关联的图标将更改为加载图像,以显示该链接处于事件状态。
问题是在第二次或更多次点击时,加载图像不会变回图标并显示多个加载图像。
如何使其只显示一张加载图像并恢复先前单击的图标。
HTML 和脚本
$('.parent a').click(function(a) {
a.preventDefault();
var $icons = $(this).siblings('i');
$($icons).replaceWith('<img class="active" src="https://cdn.dribbble.com/users/323893/screenshots/2077235/buffer.gif" width="30" height="30">');
$('img.active').not($icons).replaceWith('<i class="typcn typcn-thumbup"></i>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site1">first link</a>
</div>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site2">second link</a>
</div>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site3">third link</a>
</div>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site4">forth link</a>
</div>
最佳答案
您的实现问题是 .not($icons)
未将当前 img
元素排除为 .replaceWith()
返回从 DOM 中删除的原始元素。
缓存对 img.active
的引用,并在以后用它来替换该元素。
$('.parent a').click(function(a) {
a.preventDefault();
//Cache active images
var images = $('img.active');
//Replace i
$(this).siblings('i').replaceWith('<img class="active" src="https://cdn.dribbble.com/users/323893/screenshots/2077235/buffer.gif" width="30" height="30">');
//Replace images
images.replaceWith('<i class="typcn typcn-thumbup"></i>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site1">first link</a>
</div>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site2">second link</a>
</div>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site3">third link</a>
</div>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site4">forth link</a>
</div>
创建一个 jQuery 对象并将其与 .not()
和 .replaceWith()
函数一起使用。
$('.parent a').click(function(a) {
a.preventDefault();
var image = $('<img class="active" src="https://cdn.dribbble.com/users/323893/screenshots/2077235/buffer.gif" width="30" height="30">');
$(this).siblings('i').replaceWith(image);
$('img.active').not(image).replaceWith('<i class="typcn typcn-thumbup"></i>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site1">first link</a>
</div>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site2">second link</a>
</div>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site3">third link</a>
</div>
<div class="parent">
<i class="typcn typcn-thumbup"></i>
<a href="site4">forth link</a>
</div>
关于javascript - jQuery 在单击时动态更改图标功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52252764/