I gave my <img>
a special attribute
like this:
我给了我的这样的特殊属性:
<img src="image.png" _percent="0.01">
Now I want to get the value of _percent
with jQuery (or basic javascript)
I tried
现在我想用jQuery(或基本的javascript)获得_percent的值我尝试过
$("img").attr("_percent");
but this returns undefined
.
但这会返回undefined。
Does anyone know what to do?
有谁知道该怎么办?
3 个解决方案
#1
10
You shouldn't use attributes like that but do this:
你不应该使用这样的属性,但这样做:
<img src="image.png" data-percent="0.01">
and then:
接着:
$("img").data("percent");
#2
2
It's probably not liking your _percent
attribute. I would use a data- attribute instead:
它可能不喜欢你的_percent属性。我会改用数据属性:
<img src="image.png" data-percent="0.01">
and then
接着
$("img").attr("data-percent");
or even
甚至
$("img").data("percent");
Just note that, if you have more than one image anywhere on your page, either of the above ways of accessing your percent value will only give you the value attached to the first image jQuery finds. But I assume this was just a simplified piece of code.
请注意,如果页面上的任何位置都有多个图像,则上述访问百分比值的方法只会为您提供附加到jQuery找到的第一个图像的值。但我认为这只是一段简化的代码。
#3
0
That's what the data attribute is for.
这就是数据属性的用途。
<img src="image.png" data-percent="0.01">
$("img").attr("data-percent");
$( “IMG”)ATTR( “数据百分比”)。
#1
10
You shouldn't use attributes like that but do this:
你不应该使用这样的属性,但这样做:
<img src="image.png" data-percent="0.01">
and then:
接着:
$("img").data("percent");
#2
2
It's probably not liking your _percent
attribute. I would use a data- attribute instead:
它可能不喜欢你的_percent属性。我会改用数据属性:
<img src="image.png" data-percent="0.01">
and then
接着
$("img").attr("data-percent");
or even
甚至
$("img").data("percent");
Just note that, if you have more than one image anywhere on your page, either of the above ways of accessing your percent value will only give you the value attached to the first image jQuery finds. But I assume this was just a simplified piece of code.
请注意,如果页面上的任何位置都有多个图像,则上述访问百分比值的方法只会为您提供附加到jQuery找到的第一个图像的值。但我认为这只是一段简化的代码。
#3
0
That's what the data attribute is for.
这就是数据属性的用途。
<img src="image.png" data-percent="0.01">
$("img").attr("data-percent");
$( “IMG”)ATTR( “数据百分比”)。