来自php函数的Jquery调用

时间:2015-06-12 14:11:15

标签: javascript php jquery

我有一个包含多个链接的页面,我想在单击链接时执行Jquery功能。我想发送附带链接的值。不幸的是,我的Jquery函数没有被执行。

这是来自php文件的代码片段。

  foreach ($ties as $tie) {
      echo "<a href='#' id ='species'><em>{$tie}</em></a></br>";
  }

在我的jquery run方法中,代码片段如下所示:

 $("#species").click(function(){
      alert("Hi");
  }

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

你好,如前所述你不应该在循环中使用id,因为id在整个页面的上下文中应该是唯一的。你应该使用类。

foreach ($ties as $tie) {
    echo "<a class="species" href="somepage.php?tie=$tie"><em>{$tie}</em></a></br>";
}

$(".species").click(function() {
    // This is the clicked anchor.
    console.log(this.href);
});

您还可以使用html5数据属性来存储例如tie id&#39; s。供将来参考。

foreach ($ties as $tie) {
    echo "<a class="species" href="#" data-tie="$tieID"><em>{$tie}</em></a></br>";
}

$(".species").click(function() {
    // This is the clicked anchor.
    console.log($(this).data("tie"));
});