php include之后javascript无法工作



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

我的脚本有一个:

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

这似乎就是问题所在。在header.php和index.php(其中包括头)中,我都加载了jquery.js。当我从头中删除此文件时,autogrow会起作用,但我的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("answerbox");

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

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

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

创建一个文件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');

此线程可能会回答您的问题

检查jQuery是否包含在Header(Joomla)中

它与PHP包含文件无关。jQuery足够聪明,如果您多次包含它,它就可以自己解决问题。

这是autogrow插件代码,这是不可靠的。

编辑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>

现在两者应该同时工作。

最新更新