【问题标题】:javascript not working after php includephp包含后javascript不起作用
【发布时间】:2011-06-16 11:10:17
【问题描述】:

我正在尝试将 javascript 两次应用于一个简单的 html 文本区域。我有 onfocus 和 autogrow(实际上是 jquery)。似乎我只能让其中一个工作,但不能同时工作。

我的脚本有一个:

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

这似乎是问题所在。在 header.php 和 index.php(包含标题)中,我都加载了 jquery.js。当我从标题中删除此文件时,自动增长工作但不是我的 onfocus 事件(清除默认文本)。有没有办法包含另一个文件而不会使两者相互影响。由于代码太长,我无法提供代码。

这是我的 onfocus 代码:

<script type='text/javascript'>
    function addEvents(id) {
var field = document.getElementById(id);
field.onfocus = function () {
    if (this.value == "Answer this problem...") {
        this.value = "";
    } 
};
field.onblur = function () {
    if (this.value == "") {
        this.value = "Answer this problem...";
    } 
};

} addEvents("答案框");

【问题讨论】:

  • 您必须发布更多代码才能让我们提供帮助。加载 jQuery 两次会失败,因为它会尝试重新定义相同的函数。
  • 我的脚本也有 ,这并没有向我们展示完整的问题定义,请进一步澄清...
  • @devraj 相信我,你不想对代码进行排序。感谢您的建议,但是 header.php 和 index.php 都需要单独使用 jquery。我怎样才能只加载一次?

标签: php jquery


【解决方案1】:

规则 1:只加载一次 jquery!。您将两次加载到同一页面。因此,将其从稍后加载的文件中删除。

我假设你在 index.php 中做的第一件事是包含 header.php,所以从 index.php 中删除 jquery 加载。

【讨论】:

  • 我将 jquery.js 和 autogrow.js 都移到了 header.php 并从 index.php 中删除了它们。我得到了 autogrow 的工作,但是现在,onfocus 明文将无法工作
【解决方案2】:

将您的脚本放在一个单独的文件中,并使用 php include_once 函数将其包含在每个页面中。

创建一个文件jquery.php并添加以下内容。

<script type='text/javascript' src='jquery.js'></script> <script type="text/javascript" src="autogrow.js"></script>

在 header.php 中

include_once('jquery.php');

在 index.php 中

include_once('header.php');
include_once('jquery.php');

【讨论】:

  • @jagadeesan 是的,我使用了 include_once 和脚本 jquery.js。我应该尝试重命名 jquery 文件吗?
  • 我实际上是使用下面的代码来加载autogrow和jquery(我用这种方法在两个文件中加载jquery)
  • 谢谢。我得到了 jquery 的东西,但由于某种原因,当我单击框时,我的 javascript onfocus 现在无法工作。我不知道为什么这两个事件是相关的
【解决方案3】:

这个帖子可能会回答你的问题

Check if jQuery is included in Header (Joomla)

【讨论】:

    【解决方案4】:

    它与 PHP 包含文件无关。如果你多次包含它,jQuery 足够聪明,可以自行解决。

    这是不可靠的自动增长插件代码。

    编辑query.autogrowtextarea.js 文件。将行 this.onfocus = grow; 更改为 jQuery(this).focus(grow);

    然后是您的 Javascript 代码,我已将其更改为使用 jQuery 库(主要是因为它的代码要少得多,可以使其与 IE6+ 等旧版浏览器兼容)。

    function addEvents(id) {
        var field = jQuery('#' + id);
        field.focus(function () {
            if (this.value == "Answer this problem...") {
                this.value = "";
            }
        });
    
        field.blur(function () {
            if (this.value == "") {
                this.value = "Answer this problem...";
            }
        });
    }
    addEvents("answerbox");
    </script>
    

    现在两者应该同时工作。

    【讨论】:

    • onblur 怎么样,我为自己是业余爱好者而道歉,但是 yourHandlerHere 应该放什么?
    • 我已经在我原来的问题中发布了代码以便于查看
    猜你喜欢
    • 2016-02-17
    • 2017-06-29
    • 2017-09-20
    • 1970-01-01
    • 2015-02-05
    • 2011-03-30
    • 1970-01-01
    • 2014-05-15
    相关资源
    最近更新 更多