Why do you need the + between variables in javascript?
Why does this line work
$('#body-image').css("background-image", 'url('+ backg开发者_如何学Goroundimage +')');
but not this one
$('#body-image').css("background-image", 'url('backgroundimage')');
or this one
$('#body-image').css("background-image", 'url(backgroundimage)');
backgroundimage
is a JavaScript variable. The concatenation operator in JavaScript is +, so to put a string together with a variable, you do 'some string ' + someVariable
. Without the +'s, JavaScript wouldn't know what to do with your variable (and in your third example, wouldn't even know that it was a variable).
You need to concat the string with the variable backgroundimage
. So you use "+" for this.
That's why this doesn't work.
$('#body-image').css("background-image", 'url('backgroundimage')');
And the secont doesn't work because there is no image called 'backgroundimage'.
$('#body-image').css("background-image", 'url(backgroundimage)');
Because you are building a string. You are missing the line where backgroundimage gets a value:
var backgroundimage = "someimage.gif";
$('#body-image').css("background-image", 'url('+ backgroundimage +')');
becomes:
$('#body-image').css("background-image", 'url(someimage.gif)');
it's concatenating the string. let's say backgroundimage is 'foo.jpg, then
'url('+backgroundimage+')' = 'url(foo.jpg)'
In JavaScript, a string literal (i.e., "I am a string") is actually treated like a String object (though, strictly speaking, it isn't - see the MDC documentation - but we can ignore the difference at this level). The following two lines are equivalent:
var letters = "ABC", numbers = "123";
var letters = new String("ABC"), numbers = new String("123");
Strings are concatenated using either the + operator or the String.concat method, either of which join 2 or more strings in a left-to-right order and return the result. So in order to get "ABC123", we can do any of the following:
"ABC" + "123"
"ABC" + numbers
letters + "123"
letters + numbers
"ABC".concat("123")
"ABC".concat(numbers)
letters.concat("123")
letters.concat(numbers)
but not:
letters"123"
"ABC"numbers
lettersnumbers
"lettersnumbers"
which are all, effectively, the same thing that you were trying to do in your examples.
精彩评论