简体   繁体   English

jQuery 更新数据属性时 $.data() 未返回正确的值

[英]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.我不确定为什么 $.data 在更新数据属性后没有返回正确的值,即使该元素在萤火虫中具有正确的值。

Demo: http://jsfiddle.net/gv5cR/演示: 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() 您应该使用.data()设置数据

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

Demo ---> http://jsfiddle.net/gv5cR/2/ 演示---> 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: 由于您已经使用.attr()来设置data-price值,因此需要使用.attr()而不是.data()来获得该值:

$('#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. data-*属性仅在内部jQuery缓存中未找到时才用于初始化数据值。一旦将值复制到jQuery数据缓存中,对该属性所做的任何更改将不会反映在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. 如果要更新jQuery数据中的值,则必须使用data api ,而不是更改data-*属性。

Demo: Fiddle 演示: 小提琴

Just use只需使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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