duanli9930
duanli9930
2015-09-04 22:16
浏览 36

javascript追加Php echo?

I try to append something to a div over a Php echo

Includes

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

Php Code

<?php echo "<script type='text/javascript' >$('.notificationsBody').prepend('Hello World');</script>"; ?>

My Div Code

<div class="notificationsBody">TESTING DIV<br></div>

Is this possible and if yes why isnt this working ? My Console is empty too. If not is there a other way to realize a Div appending over a Php Echo ?

Hint: I need a Php echo if its possible.

This is my complete index.php Page

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        "http://www.w3.org/TR/html4/loose.dtd">



<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Test</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

</head>
<body>


<?php echo "<script type='text/javascript' >$('.notificationsBody').prepend('Hello World');</script>"; ?>
<div class="notificationsBody">TESTING DIV<br></div>

</body>



</html>

What i want at the end is like you have a Class and call the Function

<?php echo $myclass->theechofunction(); ?>

Then this will echo the Javascript which appending a Div to my Wrapper.

Yes its a bit crazy / difficult but thats what i need.

Thanks for every Answer.

EDIT

The Site Quellcode after calling the site

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>



<script type='text/javascript' >$('.notificationsBody').prepend('Hello World');</script>

<div class="notificationsBody">TESTING DIV<br></div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyu9433
    douyu9433 2015-09-04 23:33
    已采纳

    You have two problems. First, you're loading two versions of jQuery, that will probably cause conflicts. Either load jQuery from ajax.googleapis.com or code.jquery.com, but not both.

    Second, the Javascript that tries to append to .notificationBody is running before you add that element to the DOM. There are two ways to solve this: either move the code that echoes the <script> tag to after you echo the .notificationBody DIV, or run your code in the $(document).ready() handler, which runs after the DOM is completely loaded:

    <?php echo "<script type='text/javascript' >
        $(document).ready(function() {
            $('.notificationsBody').prepend('Hello World');
        });
        </script>";
    ?>
    

    See JS & jQuery can't detect html elements, and say's they are undefined

    点赞 评论

相关推荐