javascript - 为什么 jquery 看不到 html 的变化?

标签 javascript jquery html ajax dom

<分区>

我发出了一个 Ajax 请求,之后我更改了一个属性值。在 DOM 中,一切都按预期发生变化。但是当我再次单击该按钮时,旧的属性值显示在控制台中。看起来他没有看到标记中的变化并加载旧数据。

$('.more_credits_first').click(function () {
	var button = $(this)
	var show = $(button).data('show');
	console.log(show)

	if (show == 'show') {
		$.get(window.location.pathname,{}).done(function(data){
			$('.tbody.main_credits').append(data.template);
			$(button).attr('data-show', 'hide');
			$(button).text('Hide');
		})
	}	else {
		$(this).attr('data-show', 'show');
		$(this).text('More');
	}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='more_credits_first' type="button" data-show='show'>Button</button>

最佳答案

参见 the documentation :

Since jQuery 1.4.3, data-* attributes are used to initialize jQuery data. An element's data-* attributes are retrieved the first time the data() method is invoked upon it, and then are no longer accessed or mutated (all values are stored internally by jQuery).

jQuery 缓存 data()。您可以使用一个属性值来初始化它,但是 jQuery 只会查看它的内部记录。

不要将 jQuery 的 data() API 与 attr() 混合使用。也可以使用 data() 来设置值。

关于javascript - 为什么 jquery 看不到 html 的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56727093/

相关文章:

javascript - 正则表达式 4 非连续且无重复数字

javascript - 一次滚动一个 div 的按钮

javascript - 点击后退按钮后未执行 JS 代码

html - 隐藏 DIV 但在 CSS 中显示子类

javascript - Select2 multiple 创建重复值

javascript - React-dnd 中的动画

javascript - 使用 Json 如何根据数据库中的值选择单选按钮?

javascript - 自动递增 HTML 类/ID 以区分 div

html - CSS 高度 % 和 Px

javascript - 像 "React developer tools"这样的扩展是如何工作的?