2012-07-10 50 views
0

jQuery .wrap()函數允許您用任何自定義HTML包裝任何匹配的元素。但是,該功能不允許您指定HTML中您希望插入匹配元素的位置 - 它始終插入最內部元素jQuery:我如何用一個表(由多行組成)包裝一個元素?

我需要用一個相當基本的表格來包裝一個div(爲了給它添加圓角),但唯一的問題是表格有兩行,我希望我的元素出現在第二行。例如:

$("#my-div").wrap('<table> \ 
         <tr> \ 
          <td class="corner-topleft" colspan="2"></td> \ 
          <td class="corner-topright"></td> \ 
         </tr> \ 
         <tr> \ 
          <td class="corner-bottomleft"></td> \ 
          <td class="DIV-SHOULD-APPEAR-HERE"></td> \ 
          <td class="corder-bottomright"></td> \ 
         </tr> \ 
        </table>'); 

如果您嘗試執行該腳本,包()函數自動將第一表格單元格(即「角左上」)的內部匹配的元素,因爲這是「第一內大多數元素「。

如何使用jQuery將上述多行表中的元素包裝起來?

+1

您不應該再使用表格來製作圓角。 [他們現在是css的標準](http://davidwalsh.name/css-rounded-corners)。 – 2012-07-10 08:00:43

+0

@dystroy除非他想讓它向後兼容。 – freakish 2012-07-10 08:05:21

+0

不幸的是,這是一個使用IE8的公司,所以我不能使用CSS 3.0圓角的善良。 – 2012-07-10 08:36:44

回答

1

您必須手動做到這一點,是這樣的:

var div = $('#my-div'); 
var table = $('<table> \ 
         <tr> \ 
          <td class="corner-topleft" colspan="2"></td> \ 
          <td class="corner-topright"></td> \ 
         </tr> \ 
         <tr> \ 
          <td class="corner-bottomleft"></td> \ 
          <td class="DIV-SHOULD-APPEAR-HERE"></td> \ 
          <td class="corder-bottomright"></td> \ 
         </tr> \ 
        </table>'); 
table.find('.DIV-SHOULD-APPEAR-HERE').append(div.clone()); 
// Have to clone the div, because of the possible 
// circular reference in next line. 
div.replaceWith(table); 

我沒有測試它,但即使不工作,那麼你應該懂得這個想法。

相關問題