简体   繁体   English

获取下一个 DOM 元素的 ID

[英]Get ID of next DOM element

单击类后如何获取元素的ID?

Try this:尝试这个:

$(".className").click(function() {
    $(this).next().attr("id");
});
  1. $(".className") : select elements with class className $(".className") : 选择类className元素
  2. .click() : jQuery onclick handler .click() : jQuery onclick 处理程序
  3. $(this) : selects element again $(this) : 再次选择元素
  4. .next() : get next element .next() : 获取下一个元素
  5. .attr("id") : retrieve id attribute .attr("id") : 检索id属性

If you want to get it on click, add a click() handler如果您想在点击时获得它,请添加一个click()处理程序

You could use jQuery next function to select the "immediately following sibling":您可以使用 jQuery next函数来选择“紧随其后的兄弟”:

$(function() {
    $(".yourClassName").click(function() {
        let yourNextElementId = $(this).next().attr("id");
    });
});

Use next() to get the next element and use attr() to get its ID":使用next()获取下一个元素并使用attr()获取其 ID”:

 $(document).ready(function() { $('.sample_class').click(function() { alert($(this).next().attr('id')) }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="sample_class">element with class</div> <div id="sample_id">next element with id</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM