1

我正在使用 TWIG 中的循环返回锚点列表:

{% 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 在 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;

   });
  });

问题是警报总是在点击不同的锚点时返回相同的值,即使锚点显示正确(具有不同的 data-post-id 值)。即使经过数小时的思考,我真的不明白问题出在哪里,感谢您的帮助。

4

4 回答 4

4

您将不得不解决被点击的确切元素,所以而不是:

var id= $("a.show_post_anchor").attr("data-post-id");

写:

var id= $(this).attr("data-post-id");

那应该解决它。

于 2013-08-14T15:52:34.593 回答
3

尝试这个:

由于您的所有<a>标签都有.show_post_anchor类并且您$('a.show_post_anchor')在 DOM 中使用它,因此它首先会查找类.show_post_anchor,它只会获得第一个值,并$(this)表示当前单击的对象。

 $('a.show_post_anchor').click(function(e){
      var id= $(this).attr("data-post-id");
      alert(id);
      e.preventDefault();
      return false;
  });

演示

于 2013-08-14T15:52:17.330 回答
2

您再次使用选择器,它选择第一个匹配项(第一个 ID),而不是选择器的实例,如下所示:

var id= $(this).attr("data-post-id");
于 2013-08-14T15:53:09.440 回答
1
var id= $("a.show_post_anchor").attr("data-post-id"); 

它没有得到你点击的锚点,你需要从 e 中给出值

应该

    var id= $(this).attr("data-post-id"); 
于 2013-08-14T15:58:39.743 回答