Search code examples
javascriptjquerythis

Jquery - Get Attribute using "this"


This may be something very easy but i can't seem to get this to work and im not sure why. I have jquery installed and i am trying to get an attribute of "this" element when i click on it. Right now my code looks like this:

url = $(this).attr("href")

When I call this function by clicking on a link, it tells me that the var "url" is undefined. So obviously it is not picking up the "this" when i click on the link. I am trying to pass the href of an anchor tag to use as my variable.

What am i overlooking? Again, i know this is something very simple but i can't seem to figure it out so thank you for taking the time to help me.

Thanks.

<script type="text/javascript">
url = "push1";

$("a").live("click", function(event) {
    event.preventDefault();     
    url = $(this).attr("href");
})
$.ajax({
    type: "get",
    url: "/"+url+".php",
    data: "",
    dataType: "html",
    success: function(html){
        jQuery('#Right_Content').hide().html(html).fadeIn(1000);
    },

})
;
</script>

html:

<body>

<a href="push1" >Image 1</a>
<a href="push2" >Image 2</a>  

<div id="Right_Content"></div>

</body>

Solution

  • This should work for you

    $(function(){    
        $(".link").click(function(){
           var url=$(this).attr("href");
           alert(url);
            return false;
    
        });       
    
    });​
    

    Assuming you are targeting all anchor tags with a css class called "link"

    Here is the working example : http://jsfiddle.net/L99mM/2/

    Edit: As per your code posted in the question

    You should call preventDefault after your ajax call. and there is closing brackets should be after ajax call

    $("a").live("click", function(event) {      
          var targeturl = $(this).attr("href");
    
          $.ajax({
                   type: "get",
                   url: "/"+targeturl +".php",
                   data: "",
                   dataType: "html",
                   success: function(html){
                       jQuery('#Right_Content').hide().html(html).fadeIn(1000);
                   }
    
               });  // closing for  ajax
            event.preventDefault(); 
    
      });  // closing for click  event binding