我正在使用 TWIG 中的循环返回 anchor 列表:
{% for entity in entities %}
<a href="javascript:void(0);" class="show_post_anchor" data-post-id="{{ entity.id }}">{{ entity.id }}</a>
{% endfor %}
最终目标是使用 AJAX/jquery onclick anchor 在 div 中加载一些信息
$(document).ready(function() {
$('a.show_post_anchor').click(function(e){
var id= $("a.show_post_anchor").attr("data-post-id");
alert(id);
e.preventDefault();
return false;
});
});
问题在于,即使 anchor 正确显示(具有不同的 data-post-id 值),警报在不同 anchor 上的 onclick 上始终返回相同的值。经过几个小时的思考,我真的不明白问题出在哪里,非常感谢您的帮助。
最佳答案
您必须解决被单击的确切元素,因此不要:
var id= $("a.show_post_anchor").attr("data-post-id");
写:
var id= $(this).attr("data-post-id");
应该可以解决这个问题。
关于JQuery 变量始终具有相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18236320/