2

I have a javascript/jQuery setup where a page name is given. A function should then take this, get the html data of the page and alert it.

HTML

var page = $(this).attr('id');
viewPage(page);

function viewPage(page) {
    var html = pages.page;
    alert(html);
}

var pages = {
    page1: 'Content of page.....',
    [etc...]
}

However, the variable html is always returning as undefined. When I manually access the page from the pages array it works fine. What's the issue?

Thanks in advance!

user3002189
  • 95
  • 1
  • 5

2 Answers2

4

Your argument has to be evaluated as a key of your pages object.

Try:

function viewPage(page) {
  var html = pages[page];
  alert(html);
}

When you use pages.page it looks for the key 'page'. Wheras when you do pages[page] it evaluates your page argument to whatever it equals, and looks for that key on pages.

Mike Driver
  • 8,481
  • 3
  • 36
  • 37
1

First, pages is not an array, it's a javascript plain object.

Secondly, you need to use associative notation, not dot notation.

function viewPage(page) {
    var html = pages[page];
    alert(html);
}
Roamer-1888
  • 19,138
  • 5
  • 33
  • 44