开发者

jQuery : Defining elements in the object literal?

开发者 https://www.devze.com 2023-02-14 03:24 出处:网络
I am trying to define all my main variables within an object called globals. The problem is that when it comes to using a previous element such as membersTab to grab faces I get the error:

I am trying to define all my main variables within an object called globals. The problem is that when it comes to using a previous element such as membersTab to grab faces I get the error:

Uncaught TypeError: Cannot read property 'membersTab' of undefined.

What am I doing wrong?

 var globals = {
  siteWrap      : $('#siteWrap'),
  content       : $('#content'),
  membersTab    : $('#membersTab'),
  faces     : globals.membersTab.find('.member'),
  members       : {},
  mID       : globals.siteWrap.attr('mID'),
  uID       : globals.siteWrap.attr('uID'),
  mTag      : globals.siteWrap.attr('mTag'),
  uFirst        : globals.siteWrap.attr('fn'),
  uLast     : globals.siteWrap.attr('ln'),
  host      : globals.siteWrap.attr('host'),
  dialogueBox   : $('#dialogueBox'),
  screen     开发者_JAVA技巧   : $('#screen').click(function(){ closeDialogue(true); })
  }


If your definition of globals is not inside $(document).ready(), it is possible that the page is not yet loaded, hence $('#membersTab') returns an empty collection.

Moreover when you declare faces, the object globals is not yet created.

The simplest way is probably something like

globals = {};
globals.membersTab = $('#membersTab');
globals.faces = globals.membersTab.find('.member');
...


The member membersTab isn't initialized until the literal is closed.

First declare the global object. The null assignments are not necessary but are there for clarity and also gives nice code completion if the editor has that support. This could reduce typing errors.

var globals = {
    siteWrap = null,
    content = null,
    ...
};

Initialize the object once the DOM is loaded.

$(function(){
    globals.siteWrap = $('#siteWrap');
    globals.content = $('#content');
    ...
})
0

精彩评论

暂无评论...
验证码 换一张
取 消