【问题标题】:Why does jquery not see changes in html? [duplicate]为什么jquery看不到html的变化? [复制]
【发布时间】:2019-11-05 16:49:42
【问题描述】:

我发出一个 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>

【问题讨论】:

  • Access to XMLHttpRequest at 'https://stacksnippets.net/js' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.done 函数永远不会被调用,因此 data-show 在您的示例中永远不会被修改。

标签: javascript jquery html ajax dom


【解决方案1】:

the documentation:

从 jQuery 1.4.3 开始,data-* 属性用于初始化 jQuery 数据。元素的 data-* 属性在第一次调用它的 data() 方法时被检索,然后不再被访问或改变(所有值都由 jQuery 内部存储)。

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

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

【讨论】:

  • 那个。并确保您的请求成功,因为您只有 .done() 处理程序,当网络错误发生时不会运行。
  • 非常感谢帮助。
猜你喜欢
  • 2015-11-06
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 2018-11-27
  • 1970-01-01
  • 2014-10-05
相关资源
最近更新 更多