2015-07-01 27 views
2

我正在尋找替換表,它是行和單元格與div,但我發現的腳本替換每個子表和他們的後代與div,我不想。子表應該保留表格。用div替換頂級父表元素,而不是子表

我該如何定位頂級父表而不是任何子表?

$('table.calendar-header').each(function(){ 
     $(this).replaceWith($(this).html() 
      .replace(/<tbody/gi, "<div class='table'") 
      .replace(/<tr/gi, "<div class='tr'") 
      .replace(/<\/tr>/gi, "</div>") 
      .replace(/<td/gi, "<div class='td") 
      .replace(/<\/td>/gi, "</div>") 
      .replace(/<\/tbody/gi, "<\/div") 
     ); 
    }); 

我試過插入:第一個孩子和.first()到各個地方的腳本無濟於事。

以下是運行腳本之前HTML的樣子[請注意,我忽略了此代碼段中子表的內容]。您可以看到父表中有表。我希望那些保持原樣,不能被取代。

<table class="calendar-header" cellspacing="0" cellpadding="6" border="0" style=""> 
    <tbody> 
     <tr> 
      <td valign="top"> 
       <table class="calendar" cellspacing="0" cellpadding="2"></table> 
      </td> 
      <td align="center"> 
       <div class="eventNav"></div> 
      </td> 
      <td valign="top" align="right"> 
       <table class="calendar" cellspacing="0" cellpadding="2"></table> 
      </td> 
     </tr> 
    </tbody> 
</table> 
+0

http://api.jquery.com/replacewith/ – aahhaa

+0

我已經閱讀了replaceWith()上的jquery頁面,但是我沒有看到任何關於僅針對父項目或排除子項的建議。謝謝。 – david

+0

你正在做一個字符串替換?因爲當你調用'html()'時,它會返回該標籤內的所有字符串,而你只是用新字符串替換所有的tbodys。 – iWantSimpleLife

回答

2

我能夠做到這一點,如下所示。

爲了達到此目的,您的子表不能有calendar-header類。如果他們這樣做,則必須將支票if ($(obj).closest("table").hasClass("calendar-header"))更改爲父表格所獨有的內容。請注意,如果您的用戶使用的是Firefox和AdBlockPlus,則類thead的任何div將被theAd(「廣告」)誤認爲,並且您的div將被插件隱藏(它會隱藏會動態添加一個鏈接到elemhide.css)。因此,我改變所產生的類名divTabledivThead等:

$('table.calendar-header').each(function(){ 
    // It's important to go from farthest tag to the nearest. 
    $(this).find("th").each(replacer); 
    $(this).find("td").each(replacer); 
    $(this).find("tr").each(replacer); 
    $(this).find("tbody").each(replacer); 
    $(this).find("thead").each(replacer); 
    replacer(0, this); // replace the table tag 
}); 

function replacer(idx, obj) { 
    tagName = capitalizeFirstLetter($(obj).prop("tagName").toLowerCase()); 
    if ($(obj).closest("table").hasClass("calendar-header")) { 
     $(obj).replaceWith("<div class='div" + tagName + "'>" + obj.innerHTML + '</div>'); 
    } 
} 

function capitalizeFirstLetter(string) { 
    return string.charAt(0).toUpperCase() + string.slice(1); 
} 
+0

這樣做!非常感謝!!我即將放棄,只是隱藏了第一個和第三個移動TD,但他們有我真正想要包含的內容。 – david

0

每個表都有一個TD,對不對?

var cur = $('td').closest('table'); 
while (cur.closest('table').length > 1) 
{ 
    cur = cur.closest('table'); 
} 
+0

cur的最終版本將包含所有頂級表格。 – oMiKeY

+0

對不起,但我不明白這是如何處理我的當前腳本。我想也許我會先從腳本開始,然後用「cur」代替我的「this」,但那並不奏效。 – david

0

我想你需要手動提取出每個標記,並在JQuery中重建DOM。使用替換方法只會盲目地替換所有請求的字符串。