jQuery 子选择器帮助

发布于 2024-09-06 15:51:16 字数 1032 浏览 2 评论 0原文

一定有更好的方法来选择这个元素。有人可以帮我吗?我尝试过第 n 个孩子和最后一个孩子,但我没有得到它。

这是我的代码:

<li>
    <div class="pic" style="width:300px; text-align:center;">
        <img src='path/to/my/image.jpg' />
    </div>
    <p>
        <span title="<?php echo $media_title; ?>">Title: <?php echo stringDisplay($media_title,12); ?></span><br />
        <span title="<?php echo $media_filename; ?>">File: <?php echo stringDisplay($media_filename,18); ?></span><br />
        Updated: <?php echo date("n/j/y", $lastUpdated).' at '.date("h:ia",$lastUpdated); ?>
    </p>
    <a class="link" href="javascript:;" onclick="alert($(this).parent().children('.pic').children().children().children().attr('src'));" style="margin-bottom:3px;">Preview</a>
</li>

我试图从下面的链接中选择第一个 div 中图像的图像源。我能想到的最好的办法是:

alert($(this).parent().children('.pic').children().children().children().attr('src'));

There must be a better way to select this element. Can someone please help me out. I've tried nth-child and last-child, but I'm not getting it.

Here's my code:

<li>
    <div class="pic" style="width:300px; text-align:center;">
        <img src='path/to/my/image.jpg' />
    </div>
    <p>
        <span title="<?php echo $media_title; ?>">Title: <?php echo stringDisplay($media_title,12); ?></span><br />
        <span title="<?php echo $media_filename; ?>">File: <?php echo stringDisplay($media_filename,18); ?></span><br />
        Updated: <?php echo date("n/j/y", $lastUpdated).' at '.date("h:ia",$lastUpdated); ?>
    </p>
    <a class="link" href="javascript:;" onclick="alert($(this).parent().children('.pic').children().children().children().attr('src'));" style="margin-bottom:3px;">Preview</a>
</li>

I'm trying to select the image source of the image in the first div from the link below it. The best I could come up with is:

alert($(this).parent().children('.pic').children().children().children().attr('src'));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

撞了怀 2024-09-13 15:51:16

这是您要找的吗?

$(this).parent().find('div.pic>img').attr('src');

注意,我强烈建议不要使用onclick来绑定您的Javascript事件处理程序。

Is this what you're looking for?

$(this).parent().find('div.pic>img').attr('src');

N.B. I would strongly recommend not using onclick to bind your Javascript event handlers.

软糯酥胸 2024-09-13 15:51:16

这就是我要做的:

$(this).siblings('.pic').children('img').attr('src');

jQuery中的遍历方式有很多种:

This is how I would do it:

$(this).siblings('.pic').children('img').attr('src');

There are many ways to traverse in jQuery:

呆头 2024-09-13 15:51:16

查找第一个具有图像元素的同级元素并返回 src 属性。

$(this).prevAll().find('img:first').attr('src');

Find the first sibling with an image element and return the src attribute.

$(this).prevAll().find('img:first').attr('src');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文