Pregunta

I have a user chosen background color:

var _back = "#FF0000";  

Why doesn't this set the background color of my input field:

$("#input").val( _back ).css("background-color",$(this).val());  

when this does:

$("#input").val( _back ).css("background-color",$("#input").val());  

It does, however if I introduce a .each()

$("#input").val(_back).each(function(){$(this).css("background-color",$(this).val()) })
¿Fue útil?

Solución

You allready have the value in a variable. just add that in the css method:

$("#input").val( _back ).css("background-color",  _back);

Another reason this would be better, is that you dont need jQuery to start the method .val(), which saves some overhead.

The reason it doesn't work is because $(this) in the css method doesnt exist (well, it does, but its not pointing to the element you want). Functions like each or animate set the this value, css doesnt. This probably is because there are not alot of reasons to use this in css

Otros consejos

Because $(this) refers to the function you are in, but chaining the css() function on the end of the val() function doesn't nest functions, so there is no this object to refer to.

You could also simplify it by writing:

$("#input").css("background-color", _back);

The accepted answer is a reasonable work-around, but doesn’t solve your problem statement.

The problem in the line

$("#input").val( _back ).css("background-color",$(this).val());

is that $(this) is evaluated before css() is called.—And that is what always happens before you call a function: all it’s arguments will be evaluated beforehand. That $(this) is evaluated on the same level with the same context as $("#input") and both don’t know about each other.

On this line

$("#input").val(_back).each(function(){$(this).css("background-color",$(this).val()) })

both $(this) are part of the source code of the anonymous function you create and pass to each(). And each() calls this function itself, so it has the opportunity to set up this.

The “good” news is: css() eats functions, too. The API allows both:

.css( propertyName, value )
.css( propertyName, function )

If you feed it a function, css() will call that function, similar to each(), but only once, and use its return value.

You can fix your line with:

$("#input").val(_back).css("background-color", function(){return $(this).val();});

Note: you can not use the arrow function () => $(this).val() here. This is the most important difference between arrow and “normal” functions: there is no way to give arrow functions any this. They always take it from their lexical surrounding and this would introduce the problem we are trying to solve here...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top