jquery - 使用 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
并且无法在其中添加数据值
谁能帮我解决这个问题
解决方案
尝试类似:
$(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 元素
推荐阅读
- reason - ReasonML:未关闭的“(”
- excel-formula - 更改函数中的参考单元格
- javascript - 如何循环嵌套的 json 并将数据显示到其中。在角度 8
- javascript - Javascript正则表达式丢弃特定html标签中的匹配并匹配其他标签?
- apache-spark - java中的Spark Streaming Kinesis分区键和序列号日志
- artifactory - 使用 Bamboo 插件从工件下载最新工件
- c# - 将字符串转换为字符数组以提取和检查日期并忽略时间
- dicom - 如何注册私有 DICOM 标签?
- php - Laravel 迁移文件 2 外键无法创建
- reactjs - 尝试使用 npx 创建反应应用程序时出现问题