2013-03-11 39 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 
});