2011-06-16 127 views
0

我想應用JavaScript兩次到一個簡單的HTML文本。我有onfocus和autogrow(這實際上是jquery)。看來我只能得到一個或另一個工作,但從來沒有一次。JavaScript不工作後,PHP包括

我的劇本有:

<?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( 「answerbox」);

+3

您必須發佈更多代碼才能提供幫助。加載jQuery兩次會失敗,因爲它試圖重新定義相同的函數。 – Devraj 2011-06-16 11:12:02

+0

我的劇本也有<?PHP的******?>,這並不表明我們的全部問題的定義,請澄清多一點... – 2011-06-16 11:13:31

+0

@devraj相信我,你通過代碼不想要排序。感謝您的建議,但是標題。php和index.php每個都需要使用jquery獨立。我怎麼能只加載一次? – user780483 2011-06-16 11:14:21

回答

1

中有一個單獨的文件的腳本,並使用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'); 
+0

@jagadeesan是的,我用include_once和腳本jquery.js。我應該嘗試重命名jquery文件嗎? – user780483 2011-06-16 11:16:34

+0

現在查看我的答案。我編輯過。 – Jagadeesan 2011-06-16 11:17:18

+0

我實際上使用下面的代碼來加載自動增長和jquery(我用這種方法來加載jquery在這兩個文件中) – user780483 2011-06-16 11:18:05

2

原則之一:加載jQuery的只有一次!您正在將它加載兩次到同一頁面。因此請將其從稍後加載的一個文件中刪除。

我假設你在你的index.php做的第一件事是包括的header.php,所以從index.php中刪除jQuery的負載。

+0

我將jquery.js和autogrow.js都移到了header.php中,並將它們全部從index.php中移除。我有autogrow工作,但現在,onfocus明文不會工作 – user780483 2011-06-16 11:21:39

+0

您在螢火蟲或開發人員面板中看到的任何錯誤? – Shrinath 2011-06-16 12:56:24

1

它什麼都沒有做與PHP包含文件。如果你多次包含jQuery,那麼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> 

兩者現在應該同時工作。

+0

onblur怎麼樣,我爲業餘愛好者道歉,但是在你的HandlerHere中該怎麼辦? – user780483 2011-06-16 18:43:59

+0

這是我的onfocus事件代碼: – user780483 2011-06-16 18:55:04

+0

user780483 2011-06-16 18:55:15