简体   繁体   English

使用另一个元素获取DIV的HTML

[英]Getting the HTML of a DIV with another element

I have a bunch of thumbnails. 我有一堆缩略图。 Of these I know the link in my JQuery script - however, I need to get the HTML from the .caption , and I just can't make it do that. 其中我知道我的JQuery脚本中的link -但是,我需要从.caption获取HTML,而我只是不能使它这样做。

I've tried the following things 我尝试了以下方法

$('a.thumbnail').click(function() {
    $(this).closest('.caption').html()
    $(this).find('.caption').html()
    $(this).children('.caption').html()
});

Here's the HTML: 这是HTML:

<div class="thumbnail">
    <a href="#" class="thumbnail">
        <img src="{{ URL::asset($item->image) }}" alt="">
    </a>
    <div class="caption" align="center">
        {{ $item->name }}
    </div>
</div>

This would also work, since the .caption is a sibling of your a : 这也可以工作,因为.caption是您的a的兄弟姐妹:

$('a.thumbnail').click(function() {
    $(this).siblings('.caption').html();
});

Why yours don't work: 为什么你不工作:

$(this).closest('.caption').html() // .caption is not an ancestor of the a
$(this).find('.caption').html()  // .caption is not a descendant of the a
$(this).children('.caption').html() // .caption is not a child of the a

Try: 尝试:

$('a.thumbnail').click(function() {
    $(this).closest('div.thumbnail').find('.caption').html();
});

jsFiddle example jsFiddle示例

When you click the image, you need to use .closest() to traverse up to the containing div, and the use find to go back down to .find() the caption. 单击图像时,需要使用.closest()向上移动到包含div的位置,并使用find返回到.find()的标题。

您可以尝试:

$(this).parent().find('.caption').html();

Try this: 尝试这个:

$(".caption").text();

or Perhaps 也许

$(".thumbnail").find(".caption").text();

Although these might give you the entire class. 尽管这些可能会给您整个课程。 Have thought about adding ids? 考虑过添加ID? I've done this before using the Razor engine: 在使用Razor引擎之前,我已完成此操作:

 @foreach (var temp in ListOfStuffWithIds)
 {
   <tr class="class" >
       <td class="tdClass" >
          <input id="@temp.Id" type="checkbox" /></td>
        <td class="tdClass2">@temp.Id</td>
        <td>@temp.Name</td>
    </tr>  
 }

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

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