weixin_33737774 2017-07-27 09:14 采纳率: 0%
浏览 209

获取点击的<li>的ID

I have a dropdown list of items:

<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Räume <span class="caret"></span></a>
<ul class="dropdown-menu" id="Room">
  <!-- Auto-Generated: Dropdown content -->
</ul>

.. where the generated elements look like this:

<li class='LiRoom' id='Room 1'><a href='#'>R101</a></li>
<li class='LiRoom' id='Room 2'><a href='#'>R102</a></li>

.. and I want to display database entries on my website, depending on the selected <li> item's ID:

$(document).ready(function(){
  $("#Room").click(function() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          document.getElementById('accordion').innerHTML = this.responseText;
      }
    };
    xmlhttp.open("GET", "GetRoomComponents.php?q=1", true);
    xmlhttp.send();
  });
});

The 1 of GetRoomComponents.php?q=1 needs to be replaced with the <li>'s ID. But how do I access the correct one?

This answer https://stackoverflow.com/a/3545356/5790966 (replacing "#Room" with "#Room li") didn't work. If I do that, the entire function doesn't execute (tested on the latest Chrome).

  • 写回答

5条回答 默认 最新

  • weixin_33726943 2017-07-27 09:17
    关注

    Since you are clicking on li a element, use it as click event in jQuery.

    jQuery('#Room').on('click', 'li a', function() {
        var liId = jQuery(this).parent().attr('id').replace('Room ', ''); //Read ID of current pressed LI:
    
        console.log(liId); Prints either 1 or 2
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵