[英]Javascript in a Included PHP File
I have a php file (a form) that includes javascript to check if all inputs are filled. 我有一个包含javascript的php文件(一种形式),以检查是否所有输入都已填充。 When I view the php file directly the js works perfectly, but when I include the PHP file in another page the javascript no longer works. 当我直接查看php文件时,js可以正常运行,但是当我在另一个页面中包含PHP文件时,javascript将不再起作用。
My javascript code: 我的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>
This is an explanation to anyone who finds this question later. 这是对以后发现此问题的任何人的解释。 In javascript you can only attach a single function to an event handler. 在javascript中,您只能将单个函数附加到事件处理程序。 If you want to attach more, you need to chain them. 如果您想附加更多内容,则需要将它们链接起来。 Pretty much all javascript framework/libraries has some sort of method to handle event chaining. 几乎所有的javascript框架/库都有某种方法来处理事件链。
Javascript allows you to treat functions like variables. Javascript允许您将函数视为变量。 So you can assign an old onload function to a variable, then call it later within the new onload function. 因此,您可以将旧的onload函数分配给变量,然后稍后在新的onload函数中调用它。
If you are not using a framework, you can do something like this to handle event chaining. 如果不使用框架,则可以执行类似的操作来处理事件链。
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
You would call this with the following: 您可以通过以下方式调用它:
addLoadEvent(function(){
// Some code here
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.