0

我有一个 div,它在 jquery 的文档中准备好我附加 - 使用$("#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)}

我本来希望它会用子 div 的 html 内容而不是 javascript 发出警报?

完整脚本:

<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 回答