[英]Cant get an attribute of an element with jquery
I have got this html: 我有这个HTML:
<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">
I am trying to get this: 我试图得到这个:
$('body').on('click','.hostPic',function(){
console.log($(this).attr('data-name'));
});
Whenever the picture is pressed, I want to gets its data-name attribute, but it doesnt work.. I get undefined
reported when I try to retrieve the attribute. 每当按下图片时,我都想获取其data-name属性,但是它不起作用。当我尝试检索该属性时,我得到了undefined
报告。 Any reason why? 有什么原因吗?
Add the hostPic
class to that image. 将hostPic
类添加到该图像。
Additionally, you can just use .data('name')
, but it doesn't actually make a difference. 另外,您可以只使用.data('name')
,但实际上并没有什么不同。 Older browser may have trouble with .data
, but it's never been a problem for me. 较旧的浏览器可能无法使用.data
,但对我而言从来没有问题。
$('.hostPic').click(function() {
console.log($(this).data('name'));
}
Make sure your image has the class 'hostPic' and then do the following in your jQuery:- 确保您的图片具有“ hostPic”类,然后在jQuery中执行以下操作:
$('.hostPic').on('click', function() {
console.log($(this).data('name'));
}
The following code worked for me, maybe you are attaching the events wrong object, you can understand that by debugging the this
object instead of data-name
. 以下代码对我有用,也许您将事件附加到错误的对象上,可以通过调试this
对象而不是data-name
来理解。
And another thing is if you are going to use .data
just for read string you should use .attr
as the .data
caches and tries to convert the value its appropriate type like number
or JSON
it is a heavier process than .attr
. 另一件事是,如果您仅将.data
用于读取字符串,则应将.attr
用作.data
缓存,并尝试将其值转换为适当的类型(如number
或JSON
这比.attr
处理过程.attr
。
<img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt="">
$("img").click(function () { alert($(this).attr("data-name")); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.