The following code works. It creates a little dropdown menu (HTML select element) that changes the color of "MY TEST TEXT".
<script src="jquery-2.0.3.min.js"></script>
<p id="color-target">MY TEST TEXT</p>
<label for="test-menu">My Menu Label</label>
<select id="test-menu">
<option>red
<option>green
<option>blue
<option>magenta
</select>
<script>
$("#test-menu").on("change", function(e) {
$("#color-target").css("color", $(this).find("option:selected").val());
});
</script>
I wrote this code in various ways as part of a test and was surprised that it worked in this form. The mystery for me is, Why does "$(this)" refer to the "select#test-menu" element instead of the "p#color-target" element? I thought that $(this) used within the method of an object referred to the containing object, but in this code, $(this) is used within the .css() method of Object P which itself is used within an anonymous function, which is then used within the .on() method of Object S, so $(this) is simultaneously used within multiple functions. I assumed that in such a case $(this) would refer to the innermost containing object, p#color-target, but here it doesn't.
Why not?
(I'm tagging this with both jQuery and JavaScript, because I don't know whether the answer applies to jQuery's "$(this)" specifically or more generally to JavaScript's "this".)