jQuery选择php文件中包含的div元素?

时间:2018-08-07 18:08:52

标签: javascript php jquery html

我对JQuery还是很陌生,我可能会错过一些有关它的东西。

我创建了一个.php文件,其中包含我网站的标题。我将其包含在我的主要.php文件中。 “ header.php”包含一个“ div class = userbox_rectangle_full_header”,我想从加载在主“ homepage.php”中的JQuery中进行选择。

我尝试选择它以在单击“ div”时显示警报。当将Jquery加载到“ header.php”中时,没有问题,警报将正确显示。但是,将.js文件加载到“ homepage.php”中时没有任何反应。

希望您能够帮助我解决我所缺少的问题。

我在其中加载JQuery的主页:

<!DOCTYPE html>
<html>
    <head>
        <meta charset = "utf-8" />
        <title>DSI Welcome</title>
        <link rel="stylesheet" href="../css/homepage.css" />
    </head>
    <body>
        <header>
            <?php include 'header.php';?>
        </header>

        <div class="work_space" id="homepage_work_space">HOMEPAGE</div>
        <div class="work_space" id="userpage_work_space">USERPAGE</div>
    </body>
    <script src="../js/jquery-3.3.1.js"></script>
    <script src="../js/jquery_color_animation.js"></script>
    <script src="../js/script/homepage_script.js"></script>
</html>

我包含在主“ homepage.php”中的“ header.php”文件:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Header</title>
        <link rel="stylesheet" href="../css/header.css" />
    </head>
    <body>
        <header>
            <div class="userbox_rectangle_full_header">&nbsp</div>
        </header>
    </body>
    <script src="../js/jquery-3.3.1.js"></script>
    <script src="../js/jquery_color_animation.js"></script>
    <script src="../js/script/header_animation.js"></script>
</html>

最后,JQuery代码在“ homepage.php”中加载时不起作用,但是在“ header.php”中加载时起作用:

$(document).ready(function() {
    $('#homepage_work_space').on('click', function(){
        alert('hi');
    });
});

提前谢谢!

3 个答案:

答案 0 :(得分:0)

看起来您正在加载体外脚本。确保将它们加载到<head>标签中。

答案 1 :(得分:0)

您的代码中有些要知道的要点。

  1. 您的html结构错误!简单的html5结构:

    <!DOCTYPE html> <html> <head> <title>Title of the document</title> <!-- Your JQuery Main File --> </head> <body> Content of the document...... </body> </html>

  2. 在您的头部定义您的主要jquery文件。
  3. 您的文档具有2个<body>标签。 (一个您的主体,另一个包含在header.php中)
  4. </body>之前的页脚中定义脚本文件(在head中定义的jquery除外)
  5. 在您的header.php文件中不要定义任何脚本!
    玩得开心!

答案 2 :(得分:0)

这是该问题的修订历史的副本和粘贴,目的是根据操作员的描述来演示HTML标记的外观...

文件index.php

<html>
    <head>
        <script src="../js/jquery-3.3.1.js"/>
        <script src="../js/jquery_color_animation.js"/>
        <script src="../js/script/homepage_script.js"/>
    </head>
    <body>

        <?php include 'header.php'; ?>

        <!-- further content goes here -->

    </body>
</html>

文件header.php

<div class="userbox_rectangle_full_header">
    <div class="work_space" id="homepage_work_space">HOMEPAGE</div>
    <div class="work_space" id="userpage_work_space">USERPAGE</div>
</div>

文件homepage_script.js

$(document).ready(function() {
    $('.work_space').on('click', function(){
        alert('hi');
    });
});

我建议使用Twig或任何其他PHP模板引擎,它们是专门用于呈现HTML标记的框架,包括模板位等。