JQuery - Get attribute using "this"

It may be something very simple, but I can't get it to work, and I'm not sure why. I have jquery installed and I'm trying to get the attribute of the "this" element when I click on it. My code now looks like this:

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

When I call this function by clicking on the link, it tells me that var "url" is undefined. Thus, it is obvious that it does not pick up "this" when I click on the link. I am trying to pass href binding labels to use as my variable.

What am I missing? Again, I know this is something very simple, but I can’t figure it out, so thanks 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> 
+4
source share
3 answers

This should work for you.

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

Assuming you target all anchor tags with a css class called link

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

Edit: according to your code provided in the question

You must call preventDefault after your ajax call. and there are closing brackets should be after an 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 
+7
source
 <script type="text/javascript"> var url = "push1"; function getContent(){ $.ajax({ type: "get", url: "/"+url+".php", data: "", dataType: "html", success: function(html){ jQuery('#Right_Content').hide().html(html).fadeIn(1000); }); } $("a").live("click", function(event) { event.preventDefault(); url = $(this).attr("href"); getContent(); }); getContent(); </script> 
0
source

you do not need "this" for this, you need the purpose of the event:

 $("a").live("click", function(event) { event.preventDefault(); url = event.target.href; }) 

working script

http://jsfiddle.net/3LvCm/

0
source

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


All Articles