0

I'm receiving this HTML document via AJAX:

    <form enctype="multipart/form-data" method="POST" action="admin.php?do=media&action=file-upload">

    <div id="uploadForm">

        <div id="fileList">



        </div>

        <a href="#" id="selectFile">[Select File]</a>
        <a href="#" id="uploadFile">[Start Upload]</a>

    </div>

</form>

<script type="text/javascript">
    // $(function(){}); not working when data loaded with ajax request
        var ajaxUpload = new plupload.Uploader({

            runtimes: 'gears, html5, flash',
            url: 'upload.php',
            browse_button: 'selectFile',

        });


        ajaxUpload.bind('Init',function(param){
            console.log(param);
            console.log($('selectFile'));
        });

        $('#uploadFile').click(function(){
            alert('Something');
        });

        ajaxUpload.init();


</script>

When I append this to the main document, the JavaScript inside it will immediately run and not be able to find the referenced DOM elements.

It works when I add a time-out on the code, but I would like to know a better way at achieving this.

Update

Modified to reflect the true intent of the question.

4

3 に答える 3

1

これは、JavaScript が実行条件にバインドされていないため、説明した方法では不可能であり、すぐに実行されます。

AJAX 経由で受信しているドキュメント内のコードは、side を提供して関数内にラップする必要があります。

function onDocumentReady()
{
    // your code here
}

次に、読み込みコードから:

// get the HTML and JavaScript in data
$('#container').append($(data));
// fire the function to let JavaScript run
onDocumentReady();

複数のリクエストがある場合、提供側はonDocumentReady関数名にランダムなアルファベットを追加して関数を一意にする必要があります。onDocumentReady_123()

于 2012-05-22T06:52:12.663 に答える
0

コードを $(document).ready 内にラップします。これにより、DOM が読み込まれるまで JavaScript が実行されず、対象の要素がページで使用可能になります。

$(document).ready(function() {
   var ajaxUpload = new plupload.Uploader({

        runtimes: 'gears, html5, flash',
        url: 'upload.php',
        browse_button: 'selectFile',

    });


    ajaxUpload.bind('Init',function(param){
        console.log(param);
        console.log($('selectFile'));
    });

    $('#uploadFile').click(function(){
        alert('Something');
    });

    ajaxUpload.init();
});

これがどのように機能するかについて詳しくは、jQuery readyのドキュメントを参照してください。このサイトには、役に立つと思われる他の便利な jQuery コマンドに関する情報もあります。ぜひチェックして、そこにある例を試してみてください。幸運を!

アップデート:

私の理解が正しければ、サーバーから次のような HTML を取得しています。

<!-- Pulled HTML from the server using AJAX -->
<div id="uploadForm">
    <div id="fileList">
    </div>
    <a href="#" id="selectFile">[Select File]</a>
    <a href="#" id="uploadFile">[Start Upload]</a>
</div>

そして、おそらくこれに動的に注入しようとしています:

<form action=""> <!-- inject HTML here --> </form>

私の理解が正しければ、これにより、HTML を挿入し、AJAX 要求が完了して新しい DOM が挿入された後にのみ JavaScript を実行できるようになります。すべてのコードを持っているわけではないので、これは概念的な例にすぎないことに注意してください。

$.ajax({ url:"/somepathtoGetData",
    success: function(data) {

        // your HTML is in the variable "data", and this injects the HTML into
          // the form element on the page
        $('form').html( data );

        // now that the DOM elements are loaded from the AJAX request, do your
         // other stuff with the uploader here

        var ajaxUpload = new plupload.Uploader({

            runtimes: 'gears, html5, flash',
            url: 'upload.php',
            browse_button: 'selectFile',

        });


        ajaxUpload.bind('Init',function(param){
            console.log(param);
            console.log($('#selectFile')); // added # for id attr
        });

        $('#uploadFile').click(function(){
            alert('Something');
        });

        ajaxUpload.init();

    }
});
于 2012-05-22T06:50:24.940 に答える
-1

アップデート

2 つの php ファイルがあり、1 つは main.php で、そのようなコードを持っているとします: (jQuery src を含まないので、独自のものを追加してください)

<script type="text/javascript" charset="utf-8">

    $(document).ready(function(){
        $('#b').click(function(){
            $.post("ajax.php",
            {
                taskaction: "getFormAndJs"              
            },
            function(data){
                        $('body').append(data);
                        // $(document).trigger("ready");
            },
            "text");
            })
    });
</script>

<body>
    aaaaaaaaaaaaa
    <input type=button id="b" value="click" />
</body>

もう 1 つは、次のような ajax.php です。

<?php

if ($_POST['taskaction'] == 'getFormAndJs') {
    echo '
        <div id="uploadForm">222</div> <input type=button id="a" value="upload" />
        <script>
        $("#a").click(function(){
            alert(123);
        })
        </script>
    ';
}

?>

私が

$(document).trigger("ready");

か否か。

これはあなたの状況のように見えますか?

于 2012-05-22T06:52:25.503 に答える