Friend
Friend

Reputation: 1346

Using $(this) in jQuery, how to fix?

Here is my code below...

  $('.dp_top_panel_alphabet_ul li').click(function(){

  console.log($(this).attr('title'));

  });

This code works fine, my second code is below...

 $("[tagname='a']").click(function(){
    $('.dp_right_panel').hide();
    $('.dp_right_show').show();
    var a;
    $('.font_image').each(function(){
    if($(this).attr('title').substr(0, 1)=='A'){

        a += $(this)[0].outerHTML;
    }

    });
      $('.fonts_div_show').html(a);

  });

This code also works fine but now the problem is that I have to integrate both pieces of code and there is a problem:

  $('.dp_top_panel_alphabet_ul li').click(function(){

  var letter = $(this).attr('title');
  var tagme="[tagname="+letter+"]";

     $(tagme).click(function(){
    console.log("[tagname="+letter+"]");
    $('.dp_right_panel').hide();
    $('.dp_right_show').show();
    var a;
    $('.font_image').each(function(){
    if($(this).attr('title').substr(0, 1)==letter){

        a += $(this)[0].outerHTML;
    }

    });
      $('.fonts_div_show').html(a);

  });

  });

This code is not working... Because of $this keyword.

How do I fix this?

Upvotes: 1

Views: 81

Answers (2)

var $this = this;//Cache your selector here at the top
 ----------------------------------------------------
if ($this.title.substr(0, 1) == letter) {
    a += $this.outerHTML; //now use $this
}

Upvotes: 1

StuperUser
StuperUser

Reputation: 10850

If you want the element that's been clicked you should use the event.target property from the event parameter.

Upvotes: 1

Related Questions