Pergunta

What I am trying to do is rewrite content on the page depending on which object I have selected. I have some objects like so:

function floorPlan(name,rev,sqft,bedrm,bthrm) {
this.name = name;
this.rev = rev;
this.sqft = sqft;
this.bedrm = bedrm;
this.bthrm = bthrm;
}

// 1BR Plans

var a1 = new floorPlan('A1',false,557,1,1);
var a2 = new floorPlan('A2',false,652,1,1);
var a3 = new floorPlan('A3',false,654,1,1);
var a4 = new floorPlan('A4',false,705,1,1);
var a5 = new floorPlan('A5',false,788,1,1);

// The Selected plan

var currentPlan = floorPlan.a1;

I am having the user control this via a .click() function in a menu:

$('.sideNav li').click(function() {

  // Define the currentPlan
  var current = $(this).attr('id');
  var currentPlan = floorPlan.current;

});

The problem is that currentPlan keeps coming back as undefined and I have no idea why. Should I be defining currentPlan differently? I can't seem to find any resources to help me find the answer.


UPDATED:

I switched out a few parts per your suggestions:

// The Selected plan

var currentPlan = a1;

and....

// Define the currentPlan

var current = $(this).attr('id');

currentPlan = current;

However, everything is still returning undefined in the click function (not initially though).

Foi útil?

Solução

First of all $('this') should be $(this)

Secondly you're trying to use a read ID from your LI as a variable name. That doesn't work. If you store your plans in an array you can use the ID to search in that array:

var plans=Array();
plans["a1"]=new floorPlan('A1',false,557,1,1);
plans["a2"]=new floorPlan('A2',false,652,1,1);

Then your jQuery code should be altered to this:

$('.sideNav li').click(function() {
  // Define the currentPlan
  var current = $(this).attr('id');
  var currentPlan = plans[current];

  alert(currentPlan);        
});

I created a JSFiddle for this. Is this what you were looking for?

Outras dicas

Use as floorPlan.currentPlan = a1;

instead of var currentPlan = floorPlan.a1;

Please create a plunker and will correct if any issue.

I spot two errors.

When you write var inside a function, that variable is only accessible with that function. Right now you are creating a new variable in your anonymous function that is "hiding" the global variable with the same name.

So, first remove the var keyword from the assignment in the anonymous function (the one you call on "click").

Secondly I think you mean to assign floorPlan[current].

The final line should read:

currentPlan = floorPlan[current];

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top