【问题标题】:Select php included html element with jQuery使用 jQuery 选择 php 包含的 html 元素
【发布时间】:2021-03-02 22:56:02
【问题描述】:

我想用 jQuery 选择一个包含的 html 元素。我怎样才能做到这一点?

index.php

<?php
    <html>
        <head>
            ...
        </head>
        <body>
            include('file.php');
        </body>
    <html>
?>

文件.php

<?php
    echo '<div class="test">test</div>';
?>

select.js

let a = $('.test');
console.log(a); // returns undefined

【问题讨论】:

  • 确保 js 代码在 html 元素出现在 DOM 或 document.ready 事件后运行。
  • 在DOM结构中
    test
    是否显示?
  • @sergeykuznetsov 是的,它在 DOM 结构中。
  • @u_mulder 我已经尝试过使用 document.ready 但它不起作用:/
  • &lt;?php &lt;html&gt; ... Umm.... 尝试将 &lt;?php 放在 PHP 调用之前,并在再次启动 HTML 之前结束它。即&lt;?php include('file.php'); ?&gt;。代码甚至不应该像现在这样执行

标签: php html jquery dom


【解决方案1】:

尝试在页面完全加载后执行您的脚本。

$(window).on("load", function() {
   let test = $('.test');
   console.log(test);
}); 

【讨论】:

    【解决方案2】:

    代码应按如下方式组织:&lt;?php Php.Code.Goes.Here ?&gt;。这可以被 HTML 包围,例如,&lt;b&gt;&lt;?php print("HELLO!"); ?&gt;&lt;/b&gt;。这将显示:HELLO!

    所以...你看到问题了,用...

    <?php
        <html>
            <head>
                ...
            </head>
            <body>
                include('file.php');
            </body>
        <html>
    ?>
    

    HTML 是 IN PHP。你想要这个:

    <html>
        <head>
            ...
        </head>
        <body>
            <?php include('file.php'); ?>
        </body>
    <html>
    

    当然,这段代码根本不应该执行,因为&lt;?php &lt;html&gt; 不是真正有效的 PHP 语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-10
      • 2020-05-27
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多