简体   繁体   中英

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%

Your code should be like:

var squaresize = 25;

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

Your variable name is "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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