错误发生位置:在按钮点击事件里,方法中走了个$.ajax(),JQ代码是这样的:
$(".start").click(function() {
let $onlineStatue=$(this).parent().next().find("div").find("img");
//检验是否支持更改状态
if($onlineStatue.eq(4).css("display") == "block"){
//参数1
let deviceRunState = $(this).attr("data-val");
//参数2
let deviceId=$(this).parent().parent().attr("data");
$.ajax({
url: '/xxxx/'+deviceId+"/"+deviceRunState,
async: false,
success: function (data) {
if(data=="success"){
layer.alert('更改状态成功!', {icon: 1,closeBtn: 0 },function () {
//关闭弹窗
layer.closeAll();
// 按钮更改式样
$(this).toggle(); //报错具体位置
$(this).next().toggle(15);
$(this).next().toggle(15);
$(this).next().next().toggle();
});
}
}
});
}else{
layer.alert('不支持更改状态!', {icon: 2});
return;
}
})
报错原因及解决办法:
1.因为 $ .ajax()中的$ (this)已经不是我之前所处理的了,在$ .ajax()中它指的是 ajax jQuery对象本身;
2.解决办法就是在 $ .ajax()中的$ (this)调用前, 只需在单独的对象中保存$ (this)的引用。
// 定义当前对象
$this = $(this);