JQuery 隐藏并显示 div ID 不起作用



JQuery hide and show 不起作用,从 ajax 调用。但是相同的代码适用于document.ready函数。

第一个函数 test1 将在单击时通过表单调用。

这有什么原因吗?

function test1(id){  
$("#id").addClass('loading');
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: 'test',
data: {
'id': id,
},
success: function (res) {
$("#id").removeClass('loading');
if(res.status == 200){
test2(100); // hide and show does not work
}
else{
}
}
});
}

function test2(n=0){
$("#div1").hide();
$("#div2").show();
}
$( document ).ready(function() {
$("#div2").hide();
test2(0);  //works perfectly
});

res.status应该是未定义的。您可以通过写入控制台来验证这一点。此外,您可以在 else 语句中写入控制台。

if(res.status == 200){
test2(100); // hide and show does not work
}
else{
console.log('hit else statement');
}

您应该将 jqXHR 对象用于 HTTP 统计信息代码,但我几乎可以肯定在 .success(( 回调中不需要检查状态 200。相反,我认为如果你使用 jQuery 2,你应该使用 .error(( 回调,如果你使用 jQuery 3 来检查错误,你应该使用 .fail(( 回调。

只需替换类型和 url,它应该适合您。另外,我认为您在test1((中的选择器是错误的。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
.loading {background-color:black;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="loading">Loading</div>
<div id="div1">div 1</div>
<div id="div2">div 2</div>
<input type="button" value="call test1" onclick="test1('loading');" />
<script type="text/javascript">
function test1(id)
{
$("#" + id).addClass('loading');
jQuery.ajax({
type: 'GET',
dataType: 'json',
url: 'https://jsonplaceholder.typicode.com/todos/1',
data: {
'id': id,
},
success: function (res, textStatus, xhr)
{
$("#" + id).removeClass('loading');
console.log(xhr.status);
//console.log(res.status);
if (xhr.status == 200)
{
test2(100); // hide and show does not work
}
else
{
}
}
});;
}
function test2(n = 0)
{
$("#div1").hide();
$("#div2").show();
}
$(document).ready(function ()
{
$("#div2").hide();
test2(0);  //works perfectly

});
</script>
</body>
</html>

最新更新