简体   繁体   English

在HTML中添加自定义属性

[英]Adding custom attributes in HTML

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. 但是,这只是在我自己决定尝试添加自定义属性“ title”之后,而不是在某个地方读到这样做的方式之后。 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: HTML:

<img id="test_image" src="images/image1.jpg" title="Test Image">

jQuery: jQuery的:

$("#test_image").click(function()
{
    alert(this.title);
});

title isn't a custom attribute, it's a standard attribute. title不是自定义属性,而是标准属性。 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 . HTML5具有用于用户定义属性data的标准机制。 All attributes beginning with data- are reserved for the programmer to use. 所有以data-开头的属性都保留供程序员使用。 And jQuery has a method for accessing these, .data() . jQuery有一种用于访问它们的方法.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"> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM