0

すべての入力が入力されているかどうかを確認するための 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>
4

1 に答える 1

0

これは、後でこの質問を見つけた人への説明です。JavaScript では、イベント ハンドラーにアタッチできる関数は 1 つだけです。さらに付けたい場合は、それらを連鎖させる必要があります。ほぼすべての 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
});
于 2013-03-11T16:30:57.583 に答える