javascript jQuery 找到最接近 div 的图像 src

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13692923/
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-10-26 19:30:12  来源:igfitidea点击:

jQuery finding closest image src to a div

javascriptjqueryhtml

提问by thindery

if I have the following html:

如果我有以下 html:

<div class="showPin">
    <div class="pinIt" style="display: none;">
        <a href="#" onclick="window.open(&quot;http://pinterest.com/pin/create/button/?url=http://mysite.com/some-post&amp;description=Some Description&amp;media=http://mysite.com/path/to/myimage.jpg&quot;,&quot;Pinterest&quot;,&quot;scrollbars=no,menubar=no,width=600,height=380,resizable=yes,toolbar=no,location=no,status=no&quot;);return false;"><img src="images/pinbutton.jpg" class="pinbuttonImg"></a>
    </div>
    <a href="myimage.jpg">
        <img class="lazy data-lazy-ready" src="myimage.jpg" data-lazy-type="image" data-lazy-src="http://dev.papermusepress.com/stageblog/wp-content/uploads/2012/11/Fall_baby_shower_mantle2.jpg" alt="Fall Baby Shower Mantle" width="700" height="393" style="display: inline;">
    </a>
</div>

how can i get my alert function to work so it alerts the img src that is the actual image getting pinned, which has a class="lazy"always in it.

我怎样才能让我的警报功能工作,以便它提醒实际图像被固定的 img src,它class="lazy"总是在其中。

$('div.pinIt').click(function() {
    var url = $(this).closest('img.lazy').attr('src');      
    alert(url);
});

all it alerts for me is undefined. what am i doing wrong?

它提醒我的只是undefined。我究竟做错了什么?

回答by Sushanth --

$('div.pinIt').click(function() {
    var url = $(this).next('a').find('img.lazy').attr('src');      
    alert(url);
});

Closest traverses thru the ancestors. But the image is inside the sibling(anchor tag)of the div. So try it this way..

最近的traverses thru the ancestors。但图像sibling(anchor tag)div 的内部。所以试试这个方法..

If you want to use .closest()then this should work..

如果你想使用.closest()那么这应该工作..

$('div.pinIt').click(function() {
        var url = $(this).closest('.showPin').find('img.lazy').attr('src');      
        alert(url);
    });

回答by VisioN

One of the easiest ways is to go up to parent and search for image element inside:

最简单的方法之一是转到父级并在其中搜索图像元素:

$("div.pinIt").click(function() {
    var url = $(this).closest("div.showPin").find("img.lazy").attr("src");
    alert(url);
});