[英]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.