在哪里将jQuery添加到PHP文件中

时间:2018-01-05 21:24:26

标签: php jquery

这是我的jQuery

var emails = [
  'root@root.com',
  'anna@zzz.com'
];
$('input[type="radio"].st13').each(function() {
    var radio = $(this);
  var email = $(this).parent().prev('td').html();
  console.log($.inArray(email, emails));
  if ($.inArray(email, emails) != -1) {
    radio.prop('checked', true);
  }
});

有人帮我把这个jQuery放到php代码中。 Google上有很多不同的解决方案,我尝试了一些解决方案,但不是很好。我是初学者。请帮帮我。

2 个答案:

答案 0 :(得分:0)

PHP文件被解释为服务器的html文件。 PHP代码必须在php标签中才能工作。

<?php ?>

要在PHP文件中使用javascript,您必须使用脚本标记:

<script>
var emails = [
'root@root.com',
'anna@zzz.com'
];
$('input[type="radio"].st13').each(function() {
    var radio = $(this);
    var email = $(this).parent().prev('td').html();
    console.log($.inArray(email, emails));
    if ($.inArray(email, emails) != -1) {
   radio.prop('checked', true);
 }
});
</script>

答案 1 :(得分:0)

首先,您需要了解JQuery和JavaScript - 在浏览器中解释的代码,因此这段代码只是一些文本,直到它将在浏览器内部(Mozilla,Chrome和其他)。 PHP代码和PHP文件(在大多数情况下)是在服务器内部解释的简单文本文件。通常PHP只生成一些文本内容,如HTML或其他文本内容,并将其发送到浏览器。浏览器接收此生成的文本并尝试理解它。

那么,你的php文件&#34; index.php&#34;可以看起来像这样:

    <html>
        <head>
        </head>
        <body>

            <script type="text/javascript">
                $( document ).ready(function() {
                    var emails = [
                      'root@root.com',
                      'anna@zzz.com'
                    ];
                    $('input[type="radio"].st13').each(function() {
                      var radio = $(this);
                      var email = $(this).parent().prev('td').html();
                      console.log($.inArray(email, emails));
                      if ($.inArray(email, emails) != -1) {
                        radio.prop('checked', true);
                      }
                    });
                });
            </script>

            <?php

                echo 'This is the text generated by PHP :)';

            ?>

        </body>
    </html>