簡體   English   中英

獲取表格單元格的HTML,然后從中刪除某些元素

[英]Getting a table cell's HTML, then removing certain elements from it

好的,由於某種原因,我似乎無法完全獲得所需的東西。 我已經接近了,但是由於某種原因,無法完全解決這個難題。

HTML:

<table>
  <tr>
    <td>
      <a href="/path/to/larger/image.jpg"><img src="/path/to/image.jpg"/></a>
      <br/>Some caption <a href="http://somesite.com">text</a>.
    </td>
   </tr>
</table>

JavaScript:

$(function(){
  $('.fancy-gallery td > a').each(function(){
    var title = $(this).parent().html();
    $(this).attr('data-fancybox-title', title);
    $(this).attr('data-fancybox-group', 'group-' + $(this).closest('.textarea').attr('id'));
  });
});

因此,這給了我TD中的所有內容,包括第一個錨點和圖片。 我試過使用.remove(),但沒有用,我也試過使用.not,但也沒有用。

基本上,我需要刪除第一個<a/>標記和任何換行符(如<br/> )。 然后將其分配給data-fancybox-title屬性。

任何幫助表示贊賞。

克隆td,刪除anchor標簽,然后獲取文本。

$(function(){
  $('.fancy-gallery td').each(function(){
    var title = $(this).clone().find("a").remove().end().text();
    $(this).attr('data-fancybox-title', title);
    $(this).attr('data-fancybox-group', 'group-' + $(this).closest('.textarea').attr('id'));
  });
});

我找到了答案。 感謝@KevinB幫助我開始正確的道路。 這是那些希望這樣做的人的答案:

$(function(){
    $('.fancy-gallery td').each(function(){
        var title = $(this).clone().find('a:has(img), br').remove().end().html();
        $(this).children('a').has('img').attr('data-fancybox-title', title).addClass($(this).attr('id'));
    });
});

使用.text而不是.html

var title = $(this).parent().text();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM