2012-03-21 9 views
7

Sto usando questo codice relativamente semplice:jQuery/Javascript non valido lato sinistro in assegnazione

var height = help ? 'minus' : 'plus'; 
var prop = $('#properties'); 

if(height == 'minus'){ 
    prop.height(prop.height() -= 206); 
} else { 
    prop.height(prop.height() += 206); 
} 

Fallisce su entrambe le linee che l'aggiunta/sottrazione! Qualche idea?

+0

'- =' cerca di sottrarre '206' da' prop.height () 'e assegna il risultato ad esso. Ma 'prop.height()' restituisce un valore e non è una variabile. Presumo che tu voglia omettere il '='. –

risposta

7

L'operatore -= uguale operand = operand - value che nel tuo caso sarebbe simile

prop.height() = prop.height() - 206; 

che ovviamente avrà esito negativo. Hai solo bisogno dell'operatore meno per portare a termine questo compito.

prop.height(prop.height() - 206); 

lo farà.

1

non è possibile - = un metodo.

né è necessario prop.height(prop.height() - 206); o raccogliere il valore e poi - = piace ...

var h = prop.height(); 
h -= 206 
prop.height(h); 
1

prop.height() -= 206 attemtps assegnare al valore di ritorno, che non è una variabile così impossibile; uguale a (prop.height() = prop.height() - 206)

È possibile invece; prop.height(prop.height() - 206);

O (prop.height(prop.height() + (height === 'minus' ? -206 : 206));)

1
var height = help ? 'minus' : 'plus'; 
var prop = $('#properties'); 
var propHeight = prop.height(); 

if(height === 'minus'){ 
    prop.height(propHeight - 206); 
} else { 
    prop.height(propHeight + 206); 
} 
1

Hai la tua risposta, ma ho voluto parlare perché perdere tempo con un if/else per l'aggiunta o la sottrazione:

// subtract height if help is true, otherwise add height 
var heightmodifier = help ? -1 : 1; 
var prop = $('#properties'); 
var propHeight = prop.height(); 

prop.height(propHeight + (206 * heightmodifier)); 
Problemi correlati