简体   繁体   English

在$(document).ready期间无法更改$(document).ready期间添加的元素

[英]Can't change elements added during $(document).ready during $(document).ready

I've implemented a page with a list of options (job categories) that when clicked should display data (job descriptions). 我实现了一个页面,其中包含选项(职位类别)列表,单击该选项后应显示数据(职位描述)。 I am using BBQ to handle the back stack. 我正在使用烧烤来处理后筹码。

Everything works dandy, except for setting the initial selection when the user first navigates to the page. 除了在用户首次导航到页面时设置初始选择外,一切都很有效。 My code is getting called to addClass('selected') to the right element but it is like that element is not actually available when the code runs. 我的代码被调用将addClass('selected')到正确的元素,但是就像该元素在代码运行时实际上不可用。

Note that I added a debug call $('#category' + C).append('bite me'); 请注意,我添加了一个调试调用$('#category' + C).append('bite me'); to prove to myself this was NOT a problem with the stylesheet/CSS. 向自己证明这不是样式表/ CSS的问题。

Here's my code: 这是我的代码:

<script>
    function historyCallback(e) {
        var C = $.bbq.getState("category");
        if (C != undefined && C != 0) {
            // We've been navigated back to
            $('#Descriptions').empty();
            $.getJSON('/Jobs/GetJobDescriptions?' + 'JobCategory=' + C, function(descs) {
                $.each(descs, function(index, description) {
                    $('#Descriptions').append('<h3><a href="/Jobs/ShowJob?JobID=' + description.ID + '">' + description.JobTitle + '</a></h3>');
                    $('#Descriptions').append('<p>' + description.JobSummary + '</p>');
                    $('#Descriptions').append('<p><a href="/Jobs/ShowJob?JobID=' + description.ID + '">Read more...</a></p>');
                });
            });    
            $('a.jobcat').removeClass('selected');
            $('#category' + C).addClass('selected');
            $('#category' + C).append('bite me');
        }
        else { // category not specified so reset the page
            $.bbq.pushState({ category: 3 },2);
        }
    }

    function loadCategories() {
        $.getJSON('/Jobs/GetCategories', function(data) {
            var categories = data;
            $.each(categories, function(index, category) {
                addCategory(category.ID, category.CategoryName);
            });
        });
    }

    function addCategory(CatID, Name) {
        $('#Categories').append('<p><a class="jobcat" id="category' + CatID + '">' + Name + '</a></p>');
        $('#category' + CatID).click(function(event) {
            $.bbq.pushState({ category: CatID }, 2); // merge_mode=2 means wipe out
        });
    }

    $(document).ready(function () {
        $(window).bind("hashchange", historyCallback); // needed for bbq plugin to work     
        loadCategories();
        historyCallback(); 
    });   
 </script>

The first time through historyCallback , called directly from $(document).ready , C is undefined and thus the else statement executes $.bbq.pushState({ category: 3 },2); 第一次通过historyCallback ,直接从$(document).ready调用, C是未定义的,因此else语句执行$.bbq.pushState({ category: 3 },2); which sets the #has to category=3 which is my default category. 它将#has设置为category=3 ,这是我的默认类别。

This causes historyCallback to be called again, this time with C == 3 . 这会导致再次调用historyCallback ,这次使用C == 3 The three lines at the end of the if clause have no effect: if子句末尾的三行无效:

$('a.jobcat').removeClass('selected');
$('#category' + C).addClass('selected');
$('#category' + C).append('bite me');

Note these lines DO work as expected when I click on a category. 请注意,当我单击某个类别时,这些行会按预期工作。

It seems like the #category anchors created in loadCategories() are not yet available to jQuery/DOM/whatever when this code runs. 看起来在loadCategories()中创建的#category锚在此代码运行loadCategories()不适用于jQuery / DOM /。

Do I need some sort of delay ore something? 我需要某种延迟矿石吗? What am I missing? 我想念什么?

Thanks a ton. 万分感谢。

It's isn't available because the getJSON function runs asynchronously. 因为getJSON函数异步运行,所以它不可用。 The getJSON callback happens after the json data arrives from the server. json数据从服务器到达后发生getJSON回调。

Don't use a delay. 不要使用延迟。 What might work better: 什么可能会更好:

  1. Put the category selection into the callbacks. 将类别选择放入回调中。
  2. Trigger a custom event when your categories are loaded, then bind an event listener the makes your selection after. 在加载类别时触发自定义事件,然后绑定事件监听器,然后进行选择。

Looks to me like the problem is timing - you can't guarantee that the elements have been created, since they depend on whether the JSON has loaded and the related function has executed. 在我看来,问题出在时间上-您不能保证已创建元素,因为它们取决于是否已加载JSON和相关功能是否已执行。 Your code will almost certainly call historyCallback() before addCategory() ever executes. 您的代码几乎肯定会在执行addCategory()之前调用historyCallback()。 I'm not familiar with BBQ, though. 不过,我对烧烤并不熟悉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM