jQuery/Javascript 无效的左侧赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9803949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:54:17  来源:igfitidea点击:

jQuery/Javascript Invalid left-hand side in assignment

javascriptjquery

提问by benhowdle89

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?

它在执行加法/减法的两行上都失败了!有任何想法吗?

采纳答案by jAndy

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

-=运营商平等operand = operand - value而你的情况会是什么样子

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.

会做的。

回答by Yevgeny Simkin

you can't -= a method.

你不能 -= 一个方法。

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

要么你需要先 prop.height(prop.height() - 206);收集价值,然后 -= 它喜欢......

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

回答by Alex K.

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

prop.height() -= 206尝试分配给返回值,这不是一个不可能的变量;同 ( prop.height() = prop.height() - 206)

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

你可以改为; prop.height(prop.height() - 206);

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

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

回答by Joseph

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

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

回答by scott.korin

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

你已经得到了答案,但我想提一下为什么要费心使用 if/else 来进行加法或减法:

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