Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get the "this" value inside an on click function in jQuery
    text
    copied!<p>I want to use the live click function for my buttons so that it will be working on Ajax Loaded HTML, but then I learned that the new version for jQuery's live click -- <code>$(".button").live("click", function() {...})</code> -- is the one with <code>.on()</code> function.</p> <p>Since on that syntax, the element is inside the parameter, I could not retrieve that element if my element is "this". Is there any way I could retrieve it?</p> <pre><code>$(".selection-item a").each(function(){ var parent_selection = $(this).parents(".selection-item-wrapper"); // $(this).click(function(){ //This is the original function which works fine EXCEPT on Ajax Loaded HTML $(parent_selection).on("click",this,function(){ $(".selection-item a",parent_selection).removeClass("active"); $(this).addClass("active"); //This does not target my desired element which is $(".selection-item a")'s this console.log( $(this) ); // The "this" value returns the parent_selection, I want it to return the particular "this" of $(".selection-item a") read from the .each() on top of my code }); }); </code></pre> <p>This is my HTML. I am creating a simple item selection. That whenever I click on the image's anchor tag, I will add an "active" class to add css on it with borders to illustrate that the particular item was selected.</p> <pre><code>&lt;div class="selection-item-wrapper"&gt; &lt;div class="selection-item"&gt; &lt;a href="javascript:void(0);"&gt;&lt;img src="img/image1.png"&gt;&lt;/a&gt; &lt;h3&gt;Item 1&lt;/h3&gt; &lt;/div&gt; &lt;div class="selection-item"&gt; &lt;a href="javascript:void(0);"&gt;&lt;img src="img/image2.png"&gt;&lt;/a&gt; &lt;h3&gt;Item 2&lt;/h3&gt; &lt;/div&gt; &lt;div class="selection-item"&gt; &lt;a href="javascript:void(0);"&gt;&lt;img src="img/image3.png"&gt;&lt;/a&gt; &lt;h3&gt;Item 3&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload