jQuery showing div and then Disappearing

 ̄綄美尐妖づ 提交于 2019-12-01 01:37:29

问题


I apologize ahead of time if this is a simple question, I have this javascript code:

$(document).ready(function() {
    $("#results").hide();

    var html = $.ajax({ url: "ajax.php?db_list=get", async: false}).responseText;

    $("#submit").click(function () { 
        $("#results").show(); 
    });
});

I have a button that looks this:

<fieldset class="action">
        <button name="submit" id="submit">Submit</button>
</fieldset>

When I click on the Submit button I wanted to show the results div and have it stay there, but in Chrome it pops up and then immediately disappears, is this because of the hide() function at the top of my document ready?

Thanks!


回答1:


...is this because of the hide() function at the top of my document ready?

Probably. I'm guessing the page is refreshing. If you don't want that, use return false; in the handler.

$("#submit").click(function () { 
    $("#results").show();
    return false; 
});

or event.preventDefault().

$("#submit").click(function ( event ) { 
    $("#results").show();
    event.preventDefault();
});



回答2:


Have your results initially set to be hidden via CSS

/* CSS */
#results {
  display: none;
}

Not sure why you are jumping around the way you should use $.ajax. Use $.get if it's a GET request... Bind with .live because its better :). Let it be async because you don't want your server hanging in case of an error...

$(document).ready(function() {
  $('#submit').live('click', function(){
    $.get('ajax.php?db_list=get', function(data){
      $('#results').html(data);
      $('#results').show();
      return false;
    });
  });
});



回答3:


Instead of submit, use this code

<input id='submitMe' type = 'button' value = 'Submit Me' />

Now you don't have to return false; or event.preventDefault(); in your javascript



来源:https://stackoverflow.com/questions/4571835/jquery-showing-div-and-then-disappearing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!