简体   繁体   中英

jQuery $.data() not returning correct value when data attribute is updated

I have a very strange issue. Im not sure why the $.data not returning the correct value after updating the data attibute even though the element has the correct value in firebug.

Demo: http://jsfiddle.net/gv5cR/

<div>
    <input type="text" name="price" id="price"/>
</div>
<button type="button" id="submit" data-price="100">Submit</button>
<div id="result"></div>
<script>
$(document).ready(function(){
    $('#price').change(function(){

        $('#submit').attr('data-price',$(this).val());

    });

    $('#submit').click(function(){
        $('#result').html($(this).data('price'));
    });

});
<script>

You should set data using .data()

$('#submit').data('price',$(this).val());

Demo ---> http://jsfiddle.net/gv5cR/2/

Since you've used .attr() to set the data-price value, you need to use .attr() instead of .data() to get that value:

$('#result').html($(this).attr('data-price'));

Updated Fiddle

use like

$('#submit').click(function(){
    $('#result').html($(this).attr('data-price'));
});

the data-* attribute is only used to initialize the data value if not found in the internal jQuery cache... once the value is copied to jQuery data cache any change made to the attribute will not be reflected in the data value of jQuery.

If you want to update the value in the jQuery data, you will have to use the data api , instead of changing the data-* attribute.

Demo: Fiddle

Just use

$('#submit').click(function(){
    $(this).attr('data-price');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM