简体   繁体   English

jQuery隐藏和显示div ID不起作用

[英]JQuery hide and show div id does not work

JQuery hide and show does not work called from ajax. jQuery隐藏和显示无法从Ajax调用。 But the same code works on document.ready function. 但是相同的代码也适用于document.ready函数。

First function test1 will be called via form on click. 单击时将通过表单调用第一个函数test1。

Any reason to this? 有什么理由吗?

 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 should be undefined. res.status应该是未定义的。 You can verify that by writing to the console. 您可以通过写入控制台来验证。 Furthermore, you can write to the console in the else statement. 此外,您可以在else语句中写入控制台。

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

You should use the jqXHR object for HTTP stats code, but I am almost certain checking for status 200 is not necessary inside of the .success() callback. 您应该将jqXHR对象用于HTTP stats代码,但是我几乎可以肯定,在.success()回调内部不需要检查状态200。 Rather, I think you should use the .error() callback if your using jQuery 2, and the .fail() callback if you're using jQuery 3 to check for errors. 相反,我认为如果使用jQuery 2,则应使用.error()回调,如果使用jQuery 3,则应使用.fail()回调以检查错误。

Just replace the type and url and it should work for you. 只需替换类型和网址,它就可以为您工作。 Also, I think your selectors in test1() are wrong. 另外,我认为您在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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM