jQuery动态点击功能更改图标

问题描述 投票:0回答:3

我有这个带有图标的链接嵌套。单击链接后,与其关联的图标将更改为加载图像,以显示该链接处于活动状态。

问题出在第二次点击或更多,加载图像将不会更改回图标并显示多个加载图像。

如何使它只显示一个加载图像并还原以前单击的图标。

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>
javascript jquery html ajax replacewith
3个回答
1
投票

你的实现问题是qazxsw poi不排除当前的qazxsw poi元素,因为.not($icons)返回从DOM中删除的原始元素。

缓存对img的引用,并稍后使用它来替换元素。

.replaceWith()
img.active

创建一个jQuery对象,并将其与$('.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>函数一起使用。

.not()
.replaceWith()

0
投票

请试试这个: -

$('.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>');
});

0
投票

试试这个。不要用class属性替换它,在替换'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>
© www.soinside.com 2019 - 2024. All rights reserved.