Jquery : Access Data-link Attribute
i want to get data-link attribute form an image click . Following is my image tag
$(".aclick").click(function (e) {
e.preventDefault();
alert($(this).find('img').attr("data-link"));
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ahref="#"class="aclick"><imgdata-link="petroliumjelly.php"src="productsimgs/petroliumjelly.png"class="img-responsive"id="2"></a>
Solution 2:
The reason you're not getting a value is that you're getting the data-link attribute of the anchor tag as that is what represents this. If you find the child image you'll get the data-link. Here is a fiddle of it working.
<scripttype="text/javascript"language="javascript">
$(".aclick").click(function (e) {
e.preventDefault();
alert($(this).find('img').attr('data-link'));
var link = $(this).find('img').attr('data-link')
console.log(link);
});
</script>
Solution 3:
You can try this,
<scripttype="text/javascript"language="javascript">
$(".aclick").click(function (e) {
e.preventDefault();
alert($(this).find('img').attr('data-link'));
var link = $(this).find('img').attr('data-link')
console.log(link);
});
</script>
Solution 4:
In the context, $(this)
refers to the link, not the image.
To get the image instead, use:
var link = $('img', $(this)).data('link');
That gets the img
element inside the link (which is $(this)
).
Read more about the .data()
-method here: https://api.jquery.com/data/
In my opinion, it makes it a bit cleaner than using the .attr()
-method.
Solution 5:
You assign you data-link attribute in img tag,
so you have to write click event on img tag
$(".aclick img").click(function (e) {
e.preventDefault();
alert($(this).data("link"));
var link = $(this).data("link");
console.log(link);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ahref="#"class="aclick"><imgdata-link="petroliumjelly.php"src="productsimgs/petroliumjelly.png"class="img-responsive"id="2"></a>
Post a Comment for "Jquery : Access Data-link Attribute"