简体   繁体   English

为什么我的JavaScript变量不起作用?

[英]Why isn't my JavaScript variable working?

This works: 这有效:

$('.sameDiv').css('width', '25%');

But this doesn't: 但这不是:

var squaresize = 25;
$('.sameDiv').css('width', 'squaresize%');

Also, I've tried it with the percent symbol as part of the variable and that doesn't help. 此外,我已经尝试使用百分号作为变量的一部分,这没有帮助。

$('.sameDiv').css('width', 'squaresize%');

Should become 应该成为

$('.sameDiv').css('width', squaresize + '%');

I did not test it, but if you just put 'squaresize%' it will not try to reference it... rather, just read it directly as a literal string evaluating to "squaresize%" instead of 25% 我没有对其进行测试,但是如果您仅放置“ squaresize%”,它将不会尝试引用它……而是直接将其读取为评估为“ squaresize%”而不是25%的文字字符串。

Your code should be like: 你的代码应该是这样的:

var squaresize = 25;

$(".sameDiv").css('width', squaresize+'%');

Your variable name is "squaresize". 您的变量名称是“ squaresize”。 Knowing that when adding a string to an integer will produce a string as well, there is no need to convert your integer to a string. 知道在向整数添加字符串时也会生成字符串,因此无需将整数转换为字符串。 Just add the "%" to your variable value. 只需将“%”添加到变量值即可。

Using a single quote, you are setting css to value 'square%' as a static value. 使用单引号,将css设置为值'square%'作为静态值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM