开发者

Mixing PHP and jQuery

Working on the same page as before,but now I'm using it as a playground for messing around with jQuery so I can learn it for my'boss.' Unfortunately, I can't get the javascript in this file to execute, let alone give me a warning. All of the PHP and HTML on the page work perfectly, it's just the script that's the issue. What am I doing wrong?

<?php

  if( isset($_POST['mushu']) )
  {
    playAnimation();
    clickInc();
  }

  function playAnimation()
  {
     echo "<img src='cocktail-kitten.jpg' id='blur'>";
  }

  function clickInc()
  {
    $count = glob("click*.txt");

    $clicks = file($count[0]);
    $clicks[0]+=1;

    $fp = fopen($count[0], "w") or die("Can't open file");
    f开发者_Go百科puts($fp, $clicks[0]);
    fclose($fp);

    echo $clicks[0];

  }
?>

<html>

  <head>

    <title>Adobe Kitten</title>

    <script type="text/javascript" src="jquery.js"></script>

  </head>

  <body>

    <form action="<?php $_SERVER['PHP_SELF']; ?>"
          method="post">
    <input type="submit"
           value="Let's see what Mushu is up to."
           name="mushu">
    </form>

    <script>
      $(document).ready( function()
      {
        $('#blur').click( function()
        {
          $(this).blur( function()
          {
            alert('Handler for .blur() called.');
          });
        });
      });
    </script>
  </body>
</html>


You're calling playAnimation() before your <html> tag, so your html is malformed. JQuery probably can't find the #blur element because it's not actually inside your web page, much less within the <body>.

Move the if( isset($_POST['mushu'])) ... block of code somewhere after the body tag.


Check FireBug's console, or FireFox' Error Console.


Verify that jquery.js is being included, and check your error console.

Otherwise, a few obvious errors which may or may not contribute to your javascript problems:

  • You're outputting HTML in playAnimation() before your opening HTML tag
  • Your form's action attribute is blank - you need <?= or <?php echo
  • Your script tags should read <script type="text/javascript">


Like Scott said you need to echo the div in the actual body of the page. Also, I think another problem you have is you're calling .blur which is the event when your mouse leaves the image. Since you have functions like animate I think you might actually be looking for .fade http://api.jquery.com/fadeOut/. Try something like:

<script>
    $(document).ready( function()
    {
        $('#blur').click( function()
        {
            $(this).fadeOut('slow', function()
            {
                alert('All Done');
            });
        });
    });
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜