javascript - 数据属性更新后Jquery获取新值
问题描述
我正在通过 ajax 响应更新链接属性值。但是当我再次单击按钮/链接时,获取的是旧值而不是新值。
以下是我的代码;
HTML
<div class="calendar-control"><a class="evecal-month-view-control fright next-month" href="#" data-month="2" data-year="2019">Next</a><span class="text-center month-name">January 2019</span><a class="evecal-month-view-control fright prev-month" href="#" data-month="12" data-year="2018">Previous</a></div>
和 Jquery 代码。
jQuery(document).on('click', '.evecal-month-view-control', function(e){
e.preventDefault();
var month = jQuery(this).data('month');
var year = jQuery(this).data('year');
console.log(month);
_getMonthCalendar(month, year);
});
var _getMonthCalendar = function(m, y){
jQuery.ajax({
type: 'POST',
url: eventcaldata.ajaxurl,
data: {
action: 'ec_ajax_month_table',
year: y,
month: m,
nonce: eventcaldata.nonce,
},
beforeSend: function(){
console.log('sending...');
},
success: function(response){
jQuery('.next-month').attr( 'data-month', response.nextmonth.month );
jQuery('.next-month').attr( 'data-year', response.nextmonth.year );
jQuery('.prev-month').attr( 'data-month', response.prevmonth.month);
jQuery('.prev-month').attr( 'data-year', response.prevmonth.year);
}
});
}
首先在
.next-month
课堂上,data-month
属性值2
然后3
在响应后更改为。但是当我再次单击该按钮时,我得到2
了应该得到的值3
解决方案
jQuery 对象上的 .data() 方法缓存初始读取的值。随后对 .data() 的调用将首先查看 jQuery 的数据存储并向您发送该值。.attr() 不会更新数据存储,但会更新 HTML 中的属性。使用 .data() 或 .attr() 但避免混搭。
推荐阅读
- api - 沃尔玛 API - 公钥上传失败
- ios - 使用带有多个参数的 @objc 委托方法
- javascript - 我必须在 Next.js 项目中使用 express 吗?
- javascript - 如何使用 fs.writefile 创建 HTML 文件
- javascript - 下面是我一直在处理的索引页面的 html。我想编辑和删除数据表中的按钮但不工作
- python - 需要帮助找出一个循环来缩短某些代码的长度
- c - 为什么字节地址在下面的示例中只存储 2 位数字?
- windows - 用于递归遍历并查找特定文件类型的 bat 文件
- ios - 为什么尽管安装了相同的代码,但不同的设备从 HD 返回相同集合的不同顺序
- c++ - 为什么我可以在 C++ 的一个范围内重新声明变量?