jQuery .attr 检索自定义属性返回未定义

发布于 2024-11-14 13:40:42 字数 399 浏览 6 评论 0原文

我在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

青衫负雪 2024-11-21 13:40:42

我可以使用 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.

别挽留 2024-11-21 13:40:42

要检索元素的值,请使用 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.

和影子一齐双人舞 2024-11-21 13:40:42

是的,从 jQuery 1.6 开始,我认为你需要使用 .prop()而不是 attr()

Yes, since jQuery 1.6 I think you need to use .prop() instead of attr().

望笑 2024-11-21 13:40:42

您的代码似乎在 this fiddle 中运行良好,使用 jQuery 1.6

Your code appears to work fine in this fiddle, using jQuery 1.6

携余温的黄昏 2024-11-21 13:40:42

如果使用最新的 jQuery,请尝试使用:

$.prop(propertyName);

if using the latest jQuery, try with:

$.prop(propertyName);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文