jQuery 使用jQuery获取DIV中最后一个DIV的ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12120068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:20:07  来源:igfitidea点击:

get the ID of last DIV inside a DIV using jQuery

jqueryhtml

提问by brian wilson

I have the below.

我有下面的。

<div id=container>
    <div id=box1></div>
    <div id=box2></div>
    <div id=box3></div>
    <div id=box4></div>
    <div id=box5></div>
    <div id=box6></div>
</div>

What is the correct way to get the id of the last div inside container using jQuery?

使用jQuery获取容器内最后一个div的id的正确方法是什么?

回答by Codegiant

You can try this:

你可以试试这个:

jQuery Code

jQuery 代码

$(document).ready(function(){
   $('#container').children().last().attr('id');
});

回答by undefined

Try this:

尝试这个:

var id = $('#container div:last').attr('id')

回答by nnnnnn

Well you can do this:

那么你可以这样做:

$("#container div").last().attr("id")

Or if you only want to include divs that are direct children of #container(assuming your real-world code has more elements and might have divs inside the divs) change the above selector to "#container > div".

或者,如果您只想包含直接子代的 div #container(假设您的实际代码有更多元素并且 div 中可能有 div),请将上述选择器更改为"#container > div".

But note that there's no one "correct" way.

但请注意,没有一种“正确”的方式。

回答by Priyank Patel

You can use the .last()method which will help you to match the last element.

您可以使用.last()帮助您匹配最后一个元素的方法。

You can then get the id

然后你可以得到 id

$('#container div').last().attr('id');

See demo.

见演示

More on jquery .last()

更多关于 jquery .last()