Jquery var and $ (var) .css

I have this code:

$(document).ready(function() { $('.fa-crosshairs').click(function() { $('*').click(function() { var currentclass = $(this).attr('class'); }); }); $('#1color').click(function() { $('body').css({ "background-color": "black" }); }); }); 

I need to get currentclass var and then use it instead of $ ('body'). css, but I don't know how to do this.

The point is to get one element by clicking and then changing its css when I click ('# 1color')

+6
source share
2 answers

Declare a variable globally.

Here is an example of how you could do this.

 $(document).ready(function() { var elem; $('.fa-crosshairs').click(function() { elem = this; }); $('input').click(function() { $( elem).css({ "background-color": "teal", "color": "white" }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div class="fa-crosshairs">One</div> <div class="fa-crosshairs">Two</div> <div class="fa-crosshairs">Three</div> <div class="fa-crosshairs">Four</div> <div class="fa-crosshairs">Five</div> <div class="fa-crosshairs">Six</div> <input type="button" value="Change" /> 
+4
source

var currentclass = $(this).attr('class'); variable var currentclass = $(this).attr('class'); declared inside a function. so that it is available inside the function where it is declared. The scope of the variable is inside this function. You need to declare the variable as GLOBAL VARIABLE so that it is available outside the function. AREA OF VARIABLE

+1
source

Source: https://habr.com/ru/post/979694/


All Articles