jquery选择器问题

发布于 2024-09-27 15:39:43 字数 2017 浏览 9 评论 0原文

我有一个 div,在 jquery 的文档中准备好附加 - 使用 $("#div id").append('html text') 语法 - 带有 10 个左右的 div 子元素。

完成此操作后,我尝试通过 alert($(".classname")); 检查子 div 的内容,结果返回:

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)}

我希望它会用 html 内容发出警报子div而不是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>

更新: 如果我将警报替换为 setTimeout(function(){alert($(".unseen").html());},1000);setTimeout(function(){alert($(".unseen").html());},1000); 它返回预期的文本。如果我将超时暂停更改为 1 毫秒,它将再次返回 null

除了坚持延迟之外,不确定是否有“真正”的解决方法?

I have a div which in jquery's document ready I append - using $("#div id").append('html text') syntax - with 10 or so more div child elements.

once this is done I try to check the content of the child divs via alert($(".classname")); and it comes back with:

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)}

I would have expected it to alert with the html contents of the child divs and not javascript?

full script:

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

update:
definitely some kind of jquery/javascript race condition going on here, if I replace the alert with setTimeout(function(){alert($(".unseen").html());},1000); it returns the text expected. If I change the timeout pause to 1 millisecond it returns null once again.

Not sure of a 'real' workaround for this other than sticking in the delay?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

层林尽染 2024-10-04 15:39:43

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 的回调函数。

请参阅工作示例 此处

Ajax calls (like $.getJSON) are done asynchronously.

This means that when the jQuery selection is done(at the bottom of the script) the response might not be received yet (still on the way).

You have to move all the code that depends on elements created from the response in the callback function (right after the $.each(...);)

Ex:

$.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');
});

Also note that the html() function returns the html contents of only the first element in the set.

EDIT: your timeout trick works because it gives the ajax call the time it needs to complete and trigger the callback function that ads the objects to the DOM.

See working example here.

深爱成瘾 2024-10-04 15:39:43

尝试

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

我不明白为什么它返回函数文本;您确定您的 alert() 调用中刚刚有 $('.classname') 吗?也许您的 $('.classname').html 没有最终的() ?

Try

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

I don't understand why it returned function text; are you certain that you just had $('.classname') in your alert() call? Maybe you had $('.classname').html without the final ()?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文