jQuery .attr retrieving custom attribute returns undefined

别来无恙 提交于 2019-12-01 15:10:16

问题


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.


回答1:


To retrieve the value of elements, use val(). Since divs don't have values, you should use data() to set and get data.




回答2:


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.




回答3:


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




回答4:


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




回答5:


if using the latest jQuery, try with:

$.prop(propertyName);



来源:https://stackoverflow.com/questions/6303775/jquery-attr-retrieving-custom-attribute-returns-undefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!