繁体   English   中英

随附的PHP文件中的Javascript

[英]Javascript in a Included PHP File

我有一个包含javascript的php文件(一种形式),以检查是否所有输入都已填充。 当我直接查看php文件时,js可以正常运行,但是当我在另一个页面中包含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>

这是对以后发现此问题的任何人的解释。 在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
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM