drgm51600 2016-07-01 16:06
浏览 25
已采纳

我可以将javascript放在带有src的脚本标记的括号内吗? [重复]

This question already has an answer here:

I use these variables assigned by PHP in my linked javascript file below. Just wondering if its ok to do this:

<script src="js/settings.js">
var chores = <?php if ($chores == 0) echo "false"; else echo "true"; ?>;
var contacts = <?php if ($contacts == 0) echo "false"; else echo "true"; ?>;
var gyms = <?php if ($gyms == 0) echo "false"; else echo "true"; ?>;
var meetings = <?php if ($meetings == 0) echo "false"; else echo "true"; ?>;
var spirituals = <?php if ($spirituals == 0) echo "false"; else echo "true"; ?>;
</script>

Or should I do this:

<script>
    var chores = <?php if ($chores == 0) echo "false"; else echo "true"; ?>;
    var contacts = <?php if ($contacts == 0) echo "false"; else echo "true"; ?>;
    var gyms = <?php if ($gyms == 0) echo "false"; else echo "true"; ?>;
    var meetings = <?php if ($meetings == 0) echo "false"; else echo "true"; ?>;
    var spirituals = <?php if ($spirituals == 0) echo "false"; else echo "true"; ?>;
</script>
<script src="js/settings.js"></script>

Both seem to work fine. I don't know why I'm nervous about the top one.

</div>
  • 写回答

1条回答 默认 最新

  • dtgu21994537 2016-07-01 16:12
    关注

    If the js file (js/settings.js) uses the variables assigned in the document then you should include the javascript file after the variables have been assigned otherwise you're likely to get 'undefined' error.

    If js/settings.js use something like $(document).ready(... in which the variables are used after the document is loaded then either way would be fine.

    Ideally, in my opinion you should always include the script files after

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。