在ajax调用之后更新数据属性 [英] Updating data attribute after ajax call

查看:103
本文介绍了在ajax调用之后更新数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,该页面列出了许多工作,每个工作都有一个用于支付的按钮,并且该按钮具有一个data-paid属性,该属性包含是否已支付的值.

I have a page which lists a number of jobs, each job has a button for paid and the button has a data-paid attribute which contains the value of whether it's paid or not.

单击该按钮后,我会向我的路线发送一个请求,该请求将更新付款并返回成功以及是否付款的状态.

When the button is clicked, I send a request to my route which updates the payment and returns success along with the status whether its paid or not.

查看我的按钮.

<button data-id="{{ $r->id }}" data-paid="{{ $r->paid }}" class="btn btn-success btn-sm paid">Paid</button>

单击时

$('button.paid').on('click', function() {

        var job = this;
        var id =  $(this).data("id");

        $.get('/round/job/' + id + '/paid', function(data){

              $(job).data('paid',data.jh.paid);

              console.log(data.jh.paid);

        });

});

查看控制台时,如果已付费,则路由返回1;如果未付费,则返回0.

When looking at the console, if paid the route returns 1, if not paid it returns 0.

我想用1或0的值对按钮更新data-paid属性.

I want to update the data-paid attribute against the button with the value of either 1 or 0.

我认为函数可以做到这一点,但是它不会更新页面加载时保持不变的值.

I thought function would do that but it doesn't update the value it remains at the value when the page is loaded.

推荐答案

data 不是data-*属性的访问器,它比这更多或更少. data管理元素的jQuery数据缓存,该元素仅从data-*属性进行初始化.它永远不会给他们.

data is not an accessor for data-* attributes, it's both more and less than that. data manages jQuery's data cache for the element, which is only initialized from the data-* attributes. It never writes to them.

要实际更改属性值,请使用 attr ,而不要使用数据:

To actually change the attribute value, use attr, not data:

$(job).attr("data-paid", dta.jh.paid);

当然,如果您在整个代码中都使用data,并且除了作为起点之外,不关心实际的属性值,data就可以了,只是不要期望当您更改属性值时更改数据值.

Of course, if you use data throughout your code, and don't care about the actual attribute value except as a starting point, data is fine, just don't expect the attribute value to change when you change the data value.

另一面是,如果不需要data提供的其他功能,只需使用attr.

The flip side is that if you don't need the additional features data provides, just use attr.

示例:

// Get the element
var t = $("#target");

// See what its data value for "foo" is
console.log("Before: t.data('foo') = " + t.data('foo'));

// See what its *attribute* is
console.log("Before: t.attr('data-foo') = " + t.attr('data-foo'));

// Change it
t.data('foo', 'updated');

// See what its data value for "foo" is again
console.log("After:  t.data('foo') = " + t.data('foo'));

// See what its *attribute* is again:
console.log("After:  t.attr('data-foo') = " + t.attr('data-foo'));

<div id="target" data-foo="bar"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这篇关于在ajax调用之后更新数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆