I want to make an image which, when clicked, displays some additional information about the image, such as the title. Below is some code I have tried, which seems to work. However, this was just after deciding on my own to try adding a custom attribute "title", rather than reading somewhere that this was the way to do this. So, even though this works for me, I would like to know whether this is good practice, or whether there is a recommended way to do this?
HTML:
<img id="test_image" src="images/image1.jpg" title="Test Image">
jQuery:
$("#test_image").click(function()
{
alert(this.title);
});
title
isn't a custom attribute, it's a standard attribute. It gets displayed in a tooltip when you hover over the element.
You should not create custom attributes. HTML5 has a standard mechanism for user-defined attributes, data attributes . All attributes beginning with data-
are reserved for the programmer to use. And jQuery has a method for accessing these, .data()
.
$("#test_image").click(function() { alert($(this).data('title')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img id="test_image" src="images/image1.jpg" data-title="Test Image">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.