dongpanshi2839 2013-06-14 18:24
浏览 31
已采纳

查找被点击元素的ID?

Okay, I am not sure if this has been asked, exactly how I did, but sorry if yes.

Basically, I have 10 items in a list.

By running this query:

public function get10items()
{
    $this->query = $this->pdo->prepare("SELECT * FROM items LIMIT 10");
    $this->query->execute();

    while ($row = $this->query->fetch(PDO::FETCH_ASSOC))
    {
        echo '<li id="'.$row['id'].'">'.$row['name'].'</li><br />';
    }
}

This will list 10 items from the database into '<ul>'. This also will set an id to each item, with it's own number, like in the database.

Now, with jquery, I want the jquery to find the ID number of the clicked item.

For example our list:

Hello! [id55]
Hai! [id66]

I clicked on item 'Hello!'. How can I find out the ID of it upon click using jquery and then use it for future use? For example, sending ajax query, with that id, etc?

<ul class="list">
<?php echo $class->get10items(); ?>
</ul>

So basically I can use this:

$(".list").on("click", "li", function() {
    $.post("ajax.php", { get : this.id }, function() {
      blablabla
    });
});

Is that correct?

  • 写回答

6条回答 默认 最新

  • dtjpnd7517 2013-06-14 18:26
    关注

    This will trigger for every ul with li on the page. You can drill down more if the ul has an ID.

    //Using event delegation since not sure when these items are being added
    $("ul").on("click", "li", function() {
        console.log(this.id);
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助