在深度嵌套的画廊中获得href的价值 [英] Getting href value in a deeply nested gallery

查看:56
本文介绍了在深度嵌套的画廊中获得href的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找方法来获取div的最后一个孩子的href值时遇到了麻烦.基本上,布局是这样的:

I'm having trouble finding ways to get the href value for the last child of a div. Basically, the layout is like this:

<div id="slider">
    <div id="slide1" class="slides">
       <a href="items/show/1" class="link">
           <h2>Date</h2>
           <h3>Title</h3>
       </a>
    <div id="slide2" class="slides">
       <a href="items/show/2" class="link">
           <h2>Date</h2>
           <h3>Title</h3>
       </a>
    <div id="slide3" class="slides">
       <a href="items/show/3" class="link">
           <h2>Date</h2>
           <h3>Title</h3>
       </a>
    <div id="slide4" class="slides">
       <a href="items/show/4" class="link">
           <h2>Date</h2>
           <h3>Title</h3>
       </a>
    <div id="slide5" class="slides"> 
       <a href="items/show/5" class="link"> <-- trying to get this href value
           <h2>Date</h2>
           <h3>Title</h3>
       </a>
</div>

我正在尝试获取".link"的最后一个兄弟的href值,但我不能.请指出我做错了什么地方?到目前为止,这是我的jQuery代码:

I'm trying to get the href value of the last sibling of ".link", but i can't. Point me where I did wrong please? So far, here's my jQuery code:

$(document).ready(function(){

var latestUrl = $(".link").siblings(":last").attr("href");
console.log(latestUrl);
 });

但控制台返回:未定义"

but the console returns: "undefined"

[更新]我找到了解决方案:我需要等到页面加载完所有内容之后,才可以寻找最后一个孩子的href属性.此示例是一个图片库,因此加载需要相当长的时间,可能是页面加载后的一秒钟.因此,以下代码为jQuery脚本设置了延迟:

[UPDATE] I've found the solution to this: I need to wait until the page loads everything, then only I can look for the href attribute of the last child. This example is a gallery of images, so it takes quite some time to load, probably a second after the page loads. So here is the code that sets a delay for the jQuery script:

<script type="text/javascript">
window.setTimeout(function(){
alert($('.link:last').attr("href"));
}, 3000);
</script>

这将设置3秒钟的延迟.谢谢您的回答!

This sets a 3-second delay. Thank you for your answers!

推荐答案

您需要选择最后一个.slides元素.您可以使用:

You need to select the last .slides element. You could use:

此处示例

var latestUrl = $('#slider .slides:last').find('a').attr("href");
console.log(latestUrl);


或者,它也可以工作:


Alternatively, this would work too:

此处示例

var latestUrl = $('a', '#slider .slides:last').attr("href");
console.log(latestUrl);


虽然使用$('.link:last').attr('href')可能会在给定您提供的HTML的情况下起作用,但是如果#slider之外有.link元素,则不会起作用.此外,它不能保证它会出现在最后一个.slides元素中.


While using $('.link:last').attr('href') may work given the HTML you provided, it wouldn't work if there was a .link element outside of #slider. In addition, it doesn't guarantee that it will be in the last .slides element.

这篇关于在深度嵌套的画廊中获得href的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆