2013-03-11 114 views
0

我有一個包含javascript的php文件(表單),用於檢查是否所有輸入都已填充。當我直接查看php文件時,js完美工作,但是當我將PHP文件包含在另一頁中時,javascript不再有效。包含PHP文件中的Javascript

我的javascript代碼:

<script type="text/javascript" src="../js/modernizr.js"></script> 
<script type="text/javascript"> 
window.onload = function(){ 
    document.getElementById("topField").setAttribute("autocomplete","off"); 
    } 

window.onload = function() { 
    // get the form and its input elements 
    var form = document.forms[0], 
     inputs = form.elements; 
    // if no autofocus, put the focus in the first field 
    if (!Modernizr.input.autofocus) { 
     inputs[0].focus(); 
    } 
    // if required not supported, emulate it 
    if (!Modernizr.input.required) { 
     form.onsubmit = function() { 
      var required = [], att, val; 
      // loop through input elements looking for required 
      for (var i = 0; i < inputs.length; i++) { 
       att = inputs[i].getAttribute('required'); 
       // if required, get the value and trim whitespace 
       if (att != null) { 
        val = inputs[i].value; 
        // if the value is empty, add to required array 
        if (val.replace(/^\s+|\s+$/g, '') == '') { 
         required.push(inputs[i].name); 
        } 
       } 
      } 
      // show alert if required array contains any elements 
      if (required.length > 0) { 
       alert('The following fields are required: ' + 
        required.join(', ')); 
       // prevent the form from being submitted 
       return false; 
      } 
     }; 
    } 
} 

</script> 
+0

你有什麼錯誤控制檯看到了什麼? – datasage 2013-03-11 15:51:15

+0

檢查你的JS控制檯的錯誤? – 2013-03-11 15:51:46

+0

你是否將這個包含在同一目錄級別的php文件中?請注意腳本路徑 – 2013-03-11 15:51:53

回答

0

這是一個解釋的人誰以後發現這個問題。在JavaScript中,您只能將一個函數附加到事件處理程序。如果你想附加更多,你需要鏈接它們。幾乎所有的JavaScript框架/庫都有某種方法來處理事件鏈接。

Javascript允許您對待像變量這樣的函數。因此,您可以將舊的onload函數分配給變量,然後在新的onload函數中稍後調用它。

如果你沒有使用框架,你可以這樣做來處理事件鏈接。

function addLoadEvent(func) { 
    var oldonload = window.onload; 
    if (typeof window.onload != 'function') { 
    window.onload = func; 
    } else { 
    window.onload = function() { 
     if (oldonload) { 
     oldonload(); 
     } 
     func(); 
    } 
    } 
} 

您將與以下稱之爲:

addLoadEvent(function(){ 
    // Some code here 
});