Check for Page Load
I've got a set of radiobuttons on my page. When you select any one of开发者_运维问答 them, I'm forcing a postback to the server.
I default one of the radio buttons when the page initially loads. But then I do not want that default button to fire my jQuery script on the first page load because it causes an unecessary postback. Once the page loads, it's fine if later that radio button is selected, that it posts back, just not on page load.
Is there a way to check for page load in jQuery? I looked around but it's not surfacing in my search yet.
jQuery uses the ready callback for this.
$(document).ready(functionToCallHere);
This can be shortened to this, too:
$(function() {
// Anything here will be called on page load.
});
Technically, this fires as soon as the DOM finishes loading, but makes no guarantee that images will be loaded.
JavaScript itself also provides the load
/onload
event (which name it goes by depends on where you set it).
Edit: jQuery also has the $(window).load(functionToCallHere) event, but ready is usually what you want.
in the <head>
-tag include code like this:
<script type="text/javascript">
var loading = true;
</script>
You can now test for loading
in your scripts.
Set it to false, after your init code is finished like this:
$(function() {
// My init code
$("select the radio")
.val("my init value");
.change(function() {
if (loading) return;
$.post(
//...
);
});
loading = false;
});
What about using $(document).ready()? does it fit your needs?
精彩评论