0

jquery のドキュメントに div があり、$("#div id").append('html text')構文を使用して 10 個ほどの div 子要素を追加します。

これが完了したら、子divの内容を確認しようとすると、次のalert($(".classname"));ように返されます:

function(a){if(c.isFunction(a))return this.each(function(b){var d=c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)}

javascriptではなく、子divのhtmlコンテンツで警告することを期待していましたか?

完全なスクリプト:

<script type="text/javascript">
    $(document).ready(function(){

        // twitter api's base url
        var url="http://search.twitter.com/search.json?callback=?&result_type=recent&q=";
        // we'll store the search term here
        var query = "blah";
        // get the json file
        $.getJSON(url+query,function(json){
            // this is where we can loop through the results in the json object
            $.each(json.results,function(i,tweet){
                // this is where we do what we want with each tweet
                $("#results").append('<div class="tweetBox"><span class="unseen">'+tweet.created_at+'</span><div class="tweetImg"><img src="'+tweet.profile_image_url+'" width="48" height="48" /><a class="overbox" href="http://twitter.com/'+tweet.from_user+'/status/'+tweet.id+'"></a></div>'+tweet.text+' ...said '+((new Date().getTime()/1000/60)-(new Date(tweet.created_at))/1000/60).toFixed(0)+' minutes ago</div>');

            });
        });

        $("#results").height(function(){return $(window).height()-204;});
        alert($(".unseen").html());     
    });
</script>

<div id="results"></div>

更新:ここで何らかのjquery/javascript競合状態が発生していることは間違いありません。アラートを置き換えると、setTimeout(function(){alert($(".unseen").html());},1000);期待されるテキストが返されます。タイムアウト一時停止を 1 ミリ秒に変更すると、nullもう一度戻ります。

遅延に固執する以外に、これに対する「実際の」回避策がわかりませんか?

4

2 に答える 2

1

Ajax 呼び出し ( など$.getJSON) は非同期で行われます。

これは、(スクリプトの下部で) jQuery の選択が完了したときに、応答がまだ受信されていない可能性があることを意味します (まだ途中です)。

コールバック関数の応答から作成された要素に依存するすべてのコードを移動する必要があります (の直後$.each(...);)

元:

$.getJSON(url+query,function(json){
    // this is where we can loop through the results in the json object
    $.each(json.results,function(i,tweet){
        // this is where we do what we want with each tweet
        $("#results").append('<p>this element is created only when the callback is triggered</p>');
    });
    // do stuff here with all your created elements
    alert('found '+$(".unseen").length+' objects');
});

また、 html()関数は、セット内の最初の要素のみの html コンテンツを返すことに注意してください。

編集:タイムアウトのトリックは、ajax 呼び出しが完了し、オブジェクトを DOM にアドするコールバック関数をトリガーするのに必要な時間を与えるため、機能します。

ここで実際の例を参照してください。

于 2010-10-14T18:57:47.607 に答える
0

試す

alert($('.classname').html());

関数テキストが返された理由がわかりません。$('.classname')あなたはちょうどあなたの電話にあったと確信していますalert()か?多分あなたは$('.classname').html決勝なしで持っていました()か?

于 2010-10-14T17:43:50.573 に答える