Remembering what $ (this) is

I have the following script that changes the color of an object made by jquery to blue:

$(".objects_list").live('click', function(event) { $(this).css("color", "blue"); }); 

How can I remember what $ (this) is, so I can change the color again, but from another function or from an event of another object?

+4
source share
8 answers

Instead of a global variable, you can use the jQuery data () method to bind information to the document itself:

 $(".objects_list").live('click', function(event) { $(this).css("color", "blue"); $(document).data("yourObjectKey", $(this)); }); 

Then you can easily get this information later:

 $("otherSelector").click(function() { var yourObject = $(document).data("yourObjectKey"); if (yourObject != null) { yourObject.css("color", "red"); } }); 

EDIT: If an element is destroyed and recreated between two events, this method will not work. In this case, you can save the id element instead of referencing the element itself:

 $(".objects_list").live('click', function(event) { $(this).css("color", "blue"); $(document).data("yourObjectKey", this.id); }); 

Then:

 $("otherSelector").click(function() { var yourObjectId = $(document).data("yourObjectKey"); if (yourObjectId != null) { $("#" + yourObjectId).css("color", "red"); } }); 
+6
source

Set an object outside the scope.

 var thisObj; $(".objects_list").live('click', function(event) { thisObj = $(this); $(this).css("color", "blue"); }); 
+2
source
 var lastObj = null; $(".objects_list").live('click', function(event) { $(this).css("color", "blue"); lastObj = $(this); }); some_other_function() { if ( lastObj != null ) lastObj.css("color", "red"); } 
+1
source

You can add an id attribute to indicate the "clicked" element, and then other functions could select that identifier. There is no need for global variables of any type:

 $(".objects_list").live('click', function(event) { $(this).css("color", "blue"); $('#objects_list_clicked').removeAttr("id"); $(this).attr("id", "objects_list_clicked"); }); 
+1
source

Could you attach an event listener to "$ (this)" to listen when the color needs to be changed?

0
source

Not the cleanest solution, but you can assign it to a global variable:

myElement = $(this);

0
source

One option is to simply save $ (this) in a variable:

 var saved; $(".objects_list").live('click', function(event) { $(this).css("color", "blue"); saved = $(this); }); 
0
source

Try differently:

 $(".objects_list").live('click', function(event) { var $this = $(this); $(".objects_list").removeAttr('selected'); $this.attr('selected','selected'); $this.css("color", "blue"); }); 

Now your choice is not processed as javascript, but in the DOM. You can change the setting at any time and from anywhere using the subtitle code

 if($(".objects_list").attr('selected').length != 0){ var selectedTab = $(".objects_list").attr('selected'); } 
0
source

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


All Articles