jQuery .attr 检索自定义属性返回未定义
我在使用 jquery 时遇到以下问题。
我现在有这样的东西
<div id="yxz" value="1">
<span class="delete"></span>
</div>
,我有这个 fn 但它只返回“未定义”,但是如果我要求的话,它确实会返回 id 或类。
$(".delete").click(function(){
alert($(this).parent("div").attr("value"));
});
我曾经用相同的 attr 东西获得这个值。这与我现在使用 jquery 1.6.1 而不是 1.5.2 有关系吗?
感谢您的帮助。
i have the following problem using jquery.
I have sth like this
<div id="yxz" value="1">
<span class="delete"></span>
</div>
now I have this fn but it only returns "undefined", it does however return the id, or class if I ask for this.
$(".delete").click(function(){
alert($(this).parent("div").attr("value"));
});
I used to get this value with the same attr stuff. Does this have sth to do with me using the jquery 1.6.1 now instead of 1.5.2.
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我可以使用 jQuery Git 版本确认此代码片段在 Chrome 11、Firefox 4 和 IE 9 中完美运行。
编辑:对于那些建议 prop() 的人,请检查 docs。 Prop() 用于布尔属性,例如:选中、禁用等。
I can confirm this code snippet works perfectly in Chrome 11, Firefox 4 and IE 9 using the jQuery Git version.
EDIT: For the ones advising prop(), check the docs. Prop() is used for boolean attributes like: checked, disabled etc.
要检索元素的值,请使用 val()。由于 div 没有值,因此您应该使用 data() 来设置和获取数据。
To retrieve the value of elements, use val(). Since divs don't have values, you should use data() to set and get data.
是的,从 jQuery 1.6 开始,我认为你需要使用
.prop()
而不是attr()
。Yes, since jQuery 1.6 I think you need to use
.prop()
instead ofattr()
.您的代码似乎在 this fiddle 中运行良好,使用 jQuery 1.6
Your code appears to work fine in this fiddle, using jQuery 1.6
如果使用最新的 jQuery,请尝试使用:
$.prop(propertyName);
if using the latest jQuery, try with:
$.prop(propertyName);