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

发布于 2024-12-10 12:52:41 字数 2903 浏览 0 评论 0原文

我已经实现了一个包含选项列表(工作类别)的页面,单击该列表时应显示数据(工作描述)。我正在使用 BBQ 来处理后堆栈。

除了用户第一次导航到页面时设置初始选择之外,一切都运行良好。我的代码被调用到正确的元素 addClass('selected') ,但在代码运行时该元素实际上并不可用。

请注意,我添加了一个调试调用 $('#category' + C).append('bite me'); 来向自己证明这不是样式表/CSS 的问题。

这是我的代码:

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

第一次通过 historyCallback 直接从 $(document).ready 调用,C 未定义,因此 else 语句执行 $.bbq.pushState({category: 3 },2); ,将 #has 设置为 category=3 这是我的默认类别。

这会导致再次调用 historyCallback,这次使用 C == 3if 子句末尾的三行不起作用:

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

请注意,当我单击某个类别时,这些行确实会按预期工作。

当此代码运行时,似乎在 loadCategories() 中创建的 #category 锚点尚不可用于 jQuery/DOM/其他内容。

我需要某种延迟或什么东西吗?我缺少什么?

非常感谢。

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.

Note that I added a debug call $('#category' + C).append('bite me'); to prove to myself this was NOT a problem with the stylesheet/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); which sets the #has to category=3 which is my default category.

This causes historyCallback to be called again, this time with C == 3. The three lines at the end of the if clause have no effect:

$('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.

Do I need some sort of delay ore something? What am I missing?

Thanks a ton.

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

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

发布评论

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

评论(2

Saygoodbye 2024-12-17 12:52:41

它不可用,因为 getJSON 函数异步运行。 getJSON 回调在 json 数据从服务器到达后发生。

不要使用延迟。什么可能会更好:

  1. 将类别选择放入回调中。
  2. 加载类别时触发自定义事件,然后绑定事件侦听器以进行选择。

It's isn't available because the getJSON function runs asynchronously. The getJSON callback happens after the json data arrives from the server.

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.
不知所踪 2024-12-17 12:52:41

在我看来,问题在于时间 - 您无法保证元素已创建,因为它们取决于 JSON 是否已加载以及相关函数是否已执行。您的代码几乎肯定会在执行 addCategory() 之前调用historyCallback()。不过我对烧烤不太熟悉。

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. Your code will almost certainly call historyCallback() before addCategory() ever executes. I'm not familiar with BBQ, though.

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