admin管理员组

文章数量:1208155

I am using this relatively simple code:

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

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

It fails on both lines that do the adding/subtracting! Any ideas?

I am using this relatively simple code:

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

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

It fails on both lines that do the adding/subtracting! Any ideas?

Share Improve this question edited Mar 21, 2012 at 11:45 Joseph 120k30 gold badges184 silver badges237 bronze badges asked Mar 21, 2012 at 11:42 benhowdle89benhowdle89 37.5k74 gold badges207 silver badges339 bronze badges 1
  • 1 -= tries to subtract 206 from prop.height() and assign the result to it. But prop.height() returns a value and is not a variable. I assume you just want to omit the =. – Felix Kling Commented Mar 21, 2012 at 11:45
Add a comment  | 

5 Answers 5

Reset to default 8

The -= operator equals operand = operand - value which in your case would look like

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

which obviously will fail. You just need the minus operator to accomplish that task.

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

will do it.

you can't -= a method.

either you need to prop.height(prop.height() - 206); or collect the value first and then -= it like...

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

prop.height() -= 206 attemtps to assign to the return value, which is not a variable so impossible; same as (prop.height() = prop.height() - 206)

You can instead; prop.height(prop.height() - 206);

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

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

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

You've got your answer, but I wanted to mention why bother with an if/else for adding or subtracting:

// 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));

本文标签: jQueryJavascript Invalid lefthand side in assignmentStack Overflow