document.ready is getting called multiple times
Within my php app I have multiple templates that get combined to form a single page. so say your on the about us page, the template would look like this
<?php
$this->render("header.php");
?>
my about us page
<?php
$this->render("footer.php");
?>
which is just a fancy way of doing an include(). However, header.php has some javascript 开发者_如何学编程that gets ran on document.ready via the jquery framework, and so does the page that requires the header. so you have something like this
<?php
$this->render("header.php"); // has its own $(document).ready
?>
<script type="text/javascript">
$(document).ready(function(){
console.log("test");
});
</script>
my about us page
<?php
$this->render("footer.php");
?>
The bug that I'm experiencing is that document.ready is getting called once for every document.ready on the page. in the above case console shows
test
test
If I comment out the rendering of header.php, the document.ready gets called just once like I want.
Besides using a semaphore, is a better way to prevent this? I tried buffering the output, but that doesn't seem to work.
Edit: added final output per request
<script type="text/javascript">
$(document).ready(function(){
// do some javascript like highlighting
// form elements with specific classes
});
</script>
display header here
<script type="text/javascript">
$(document).ready(function(){
console.log("test");
});
</script>
my about us page
display footer
I've just tried running your final output locally and only one "test" message appears in the console, as expected.
Are you including any other JS libraries? There may be some code in the JS which you have edited out that is causing this.
I put together this demo code but wasn unable to reproduce the issue... hopefully it helps you out...
<html>
<head>
<title>test</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// do some javascript like highlighting
// form elements with specific classes
$('.some-element').css('background', '#eec');
});
</script>
display header here
<script type="text/javascript">
$(document).ready(function() {
$('body').append("<p>test</p>");
});
</script>
<p class='some-element'>
my about us page
display footer
</p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</body>
</html>
精彩评论