-1

我有一个 PHP 'if',如果它适用,它只加载某个 javascript:

(这是来自<head>我的页面)

<?PHP if ($row['jstype'] == 'myanswer')
  {
  echo '<script type="text/javascript" src="js/index.js"></script>';
  }
else
  {
  echo '';
 }
 ?>

现在,我已经检查了它适用的页面上的源代码,并且 js 出现在 html 中。但是,它没有加载。我只能假设这是因为它在从 PHP 获得指令后没有足够的时间加载。这是一个正确的假设吗?

而且,更重要的是,任何人都可以提出一种方法来做我需要做的事情吗?

4

1 回答 1

1

set up a test file index.js containing only:

alert('boo!');

Test that works with a hard-coded version of your js include line.

Prove it works.

Then add your PHP version.

PHP spits out the whole stream to the browser, so no, its nothing to do with PHP - probably something to do with relative/absolute paths in the SRC of the js defn - hence the incremental development idea above should help identify where you are going wrong. Divide and conquer.

The code you showed means there is no point in having an else, so you could shorten it to:

<?php
if ($row['jstype'] == 'myanswer')
  echo '<script type="text/javascript" src="js/index.js"></script>';
?>

Depending on how many ELSE conditions you actually do need, show them and its possible someone can suggest better ways of writing it.

于 2013-08-09T09:29:11.957 回答