0

何らかの理由で、スピナー オブジェクトは startSpin() 関数内で定義されている場合にのみ機能します。

これは動作しないコードです:

<script type="text/javascript" src="resources/js/spin.js"></script>
    <script type="text/javascript">
        var opts = {
            lines: 18, // The number of lines to draw 
            length: 40, // The length of each line
            top: 'auto', // Top position relative to parent in px
            left: 'auto' // Left position relative to parent in px
        };

         // -- not support ? 
        var target = document.getElementById('spin');
        var spinner = new Spinner(opts).spin(target);
        // -- ???
        function startSpin()
        {
            spinner.start();   
        }
        function stopSpin()
        {
            spinner.stop();  
        }

        function showStatus() {
            startSpin();
            statusDialog.show();
        }

        function hideStatus() {
            stopSpin();
            statusDialog.hide();
        }
    </script>
    <h:form id="testfm">
        <p:commandButton id="start" type="submit" 
                         ajax="false" 
                         value="test" 
                         actionListener="#{bean.test}" 
                         onclick="PrimeFaces.monitorDownload(showStatus, hideStatus)"/>
        <p:dialog modal="true" 
                  widgetVar="statusDialog" 
                  showHeader="false"
                  draggable="false" 
                  closable="false" 
                  resizable="false">
            <div id="spin" class="spinner"/>
        </p:dialog>
    </h:form>

スピナーは、spinStart 関数内で定義されている場合にのみ機能します

スクリプトの位置で遊んでみましたが、それでも同じメッセージが表示されますが、その理由は何ですか?

ありがとう

4

1 に答える 1

2

document.getElementById('spin')その関数の外で実行すると、要素id=spinがまだ作成されていないため、スピナーに null 値を与えています。内startSpinに作成すると、ユーザーからのクリック イベントに応答するため、その時点で DOM が構築され、要素が存在する可能性があります。回避策は次のとおりです。

    var spinner;  //Lave the variable out here so both functions can see it

    function startSpin() {
        var target = document.getElementById('spin');
        spinner = new Spinner(opts).spin(target);  //Actually create it here, when the element exists
        spinner.start();   
    }
    function stopSpin() {
        spinner.stop();  
    }

</body>コードをそのままにして、ドキュメントの最後、タグの直前に配置することもできます。

于 2012-07-24T02:21:07.107 に答える