首页 > 解决方案 > 使用 jquery 与兄弟姐妹一起显示数据时出现问题

问题描述

在使用 jquery 的事件$ajax加载初始屏幕时,寻找一种在 HTML 中触发请求和附加响应数据的解决方案onload

这里有我的代码,PFB

   $(document).ready(function(){
   $(function(){
       $(".clickcounter").each(function(){  
           $(this).parent().addClass('active_parent');         
	   var clicked_link = $(this).attr('href');
	   $.ajax({
	       type: "POST",
	       url: 'URL',
	       data : { 'clicked_link' : clicked_link },
	       cache: false,
	       success: function(data) {
	           $('.active_parent .count_span').text(clicked_link+' '+data);
                   $('.active_parent').removeClass('active_parent');
	       }
	   })
        });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="size-button-show-code">
	<a class="button-show-code-orng offer-button js-triggers-outclick clickcounter active" href="https://123.com" target="_blank" rel="nofollow noopener noreferrer"> Visit HomePage</a>
	<span class="count_span">1st clicks<br></span>
</div>
<div class="size-button-show-code">
	<a class="button-show-code-orng offer-button js-triggers-outclick clickcounter active" href="https://123.com" target="_blank" rel="nofollow noopener noreferrer"> Visit HomePage</a>
	<span class="count_span">2nd clicks<br></span>
</div>
<div class="size-button-show-code">
	<a class="button-show-code-orng offer-button js-triggers-outclick clickcounter active" href="https://123.com" target="_blank" rel="nofollow noopener noreferrer"> Visit HomePage</a>
	<span class="count_span">3rd clicks<br></span>
</div>
<div class="size-button-show-code">
	<a class="button-show-code-orng offer-button js-triggers-outclick clickcounter active" href="https://123.com" target="_blank" rel="nofollow noopener noreferrer"> Visit HomePage</a>
	<span class="count_span">4th clicks<br></span>
</div>

但是此代码找不到它最近的.count_span并且无法在其中添加数据值

谁能帮我解决这个问题

标签: jqueryhtml

解决方案


尝试类似:

 $(function(){
  $(".clickcounter").each(function(){
    var $self = $(this);
    $self.parent().addClass('active_parent');         
    var clicked_link = $self.attr('href');
    $.ajax({
      type: "POST",
      url: 'URL',
      data : { 'clicked_link' : clicked_link },
      cache: false,
      success: function(data) {
        $('.count_span', $self).text(clicked_link+' '+data); // this is where you need $self
        $('.active_parent').removeClass('active_parent');
        //$self.removeClass('active_parent'); is maybe better then they line above -> depends if you really want to remove that class on all element or only the current one
      }
    })
  });
});

您需要回调中的自引用来获取正确的 count_span 元素


推荐阅读