Combining PHP and jQuery?
I'm trying to run the following code:
if($thisIsSaved > 0 && $_SESSION["loggedIn"] == 1)
{
//show unsave
echo "<script>$('#unsave').show();$('#save').hide();</script>";
}
elseif($thisIsSaved == 0 && $_SESSION["loggedIn"] == 1)
{
//show save
echo "<script>$('#save').show();$('#unsave').hide();</script>";
}
else
{
echo "<script>$('#unsave').hide();$('#save').hide();</script>";
}
<button id="save">Save<开发者_JAVA百科/button>
<button id="unsave">Unsave</button>
I used to have this in pure PHP, no jQuery. What it did was, depending on the value of $thisIsSaved, it would display or not display either or both of the buttons. Now it's jQuery, and the page doesn't hold your save-state with jQuery as it can with PHP, so I have to find an alternate way of displaying and hiding the buttons in the beginning. Any help?
You need to wrap the contents within the script within a document.ready call:
...
echo "<script>$(document).ready(function() { $('#unsave').hide();$('#save').hide(); });</script>";
...
The problem is, since the execution of those scripts isn't deferred with document.ready, the jQuery commands are being run before the elements are actually parsed (since the buttons appear after the script tag).
It's usually best to make sure any jQuery that runs that touches the DOM be run within a document.ready to make sure everything has been parsed. You'll see this in most online examples.
All that being said, why offload the processing to the client? If you can output a class/style in PHP to hide/show the buttons, I'd recommend keeping that unless there is other specific client-side logic that needs to happen.
Try putting the button html before the php that generates the jquery, so that when the page is rendered the buttons are defined before you try to hide/show them.
精彩评论