最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery.data and dynamically changing HTML5 custom attributes - Stack Overflow

programmeradmin4浏览0评论

The problem:

jQuery objects html5 custom attributes DATA is being cached.
In my application I have a form with a field that has a changing custom data attribute, and this specific behavior is imperative for the functionally of the form.


What we have here:

There is an input field with some default custom attribute:

<input type="text" name="xxx" data-test="4">


Get the custom attribute

for $('input').data() the result would be { test="4" }


change custom attribute

$('input').attr('data-test','5')


Get the custom attribute - again

for $('input').data() the result would STILL be { test="4" }


Question

How can I always make sure to get all the REAL custom attributes, there can be more than one on an element, using the $.data() function? I have tried the $.removeData() before each fetch, but it cleans all the data pletely from the element so it isn't accessible any longer.

The problem:

jQuery objects html5 custom attributes DATA is being cached.
In my application I have a form with a field that has a changing custom data attribute, and this specific behavior is imperative for the functionally of the form.


What we have here:

There is an input field with some default custom attribute:

<input type="text" name="xxx" data-test="4">


Get the custom attribute

for $('input').data() the result would be { test="4" }


change custom attribute

$('input').attr('data-test','5')


Get the custom attribute - again

for $('input').data() the result would STILL be { test="4" }


Question

How can I always make sure to get all the REAL custom attributes, there can be more than one on an element, using the $.data() function? I have tried the $.removeData() before each fetch, but it cleans all the data pletely from the element so it isn't accessible any longer.

Share Improve this question edited Dec 7, 2011 at 11:48 vsync asked Dec 7, 2011 at 11:09 vsyncvsync 131k59 gold badges340 silver badges423 bronze badges 1
  • What version of jQuery are you using? – Crescent Fresh Commented Dec 7, 2011 at 11:44
Add a ment  | 

1 Answer 1

Reset to default 7

You need to do this: $('input').data( 'test' , 5 )

If you call .attr( 'test' , 5 ) you will be setting an attribute, and you are affecting it like this <input type='text' data-test='4' test='5' />

As a note, you can get specific data attributes like this: var test = $('input').data('test');

edit

For removing a specific data attribute, you can do this: jQuery.removeData( $( 'input' ) , "test" );

发布评论

评论列表(0)

  1. 暂无评论