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>
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
Approach: First, select the element which is having data attributes. We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.
The getAttribute() method is used to get the value of an attribute of the particular element. If the attribute exists, it returns the string representing the value of the corresponding attribute. If the corresponding attribute does not exist, it will return an empty string or null.
jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With