jQueryセレクターの問題
-
30-09-2019 - |
質問
私はjqueryのドキュメントで準備ができているdivを持っています私は追加します - $("#div id").append('html text')
構文-10程度のDiv Child Elements。
これが完了したら、私は子供のコンテンツを介してチェックしようとします 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ではなく、子供Divsの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
もう一度。
遅延に固執する以外に、これに対する「本当の」回避策がわかりませんか?
解決
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に広告するコールバック関数をトリガーするのに必要な時間を与えるため、動作します。
作業例を参照してください ここ.
他のヒント
試す
alert($('.classname').html());
なぜそれが関数テキストを返したのかわかりません。あなたはちょうど持っていたことを確信していますか? $('.classname')
あなたの中で alert()
電話?多分あなたは持っていた $('.classname').html
決勝なし ()
?