簡體   English   中英

jQuery如何包裝表格單元格

[英]jQuery how to wrap a table cell

我想用jquery在一行周圍添加一個包裝器。 我已經做了幾次嘗試,但是沒有能力。 我只能通過一個html模板進行填寫,但是這樣做orig.html()會丟失所有在那里的輸入選擇值。

原始HTML:

    <table><tbody>
  <tr id="myitem1"><td>I need a coat1</td></tr>
  <tr id="myitem2"><td>I need a coat2</td></tr></tbody></table>

===我想使用jQuery包裝行並添加按鈕單元格並獲得以下結果:

 <table><tbody>
  <tr id="myitem1">
   <td>
    <table><tbody>
     <tr><td>I need a coat1</td></tr>
    </tbody></table>
   </td>
   <td><input type="button" value="click1"></td>     
  </tr>
  <tr id="myitem2">
   <td>
    <table><tbody>
     <tr><td>I need a coat2</td></tr>
    </tbody></table>
   </td>
   <td><input type="button" value="click1"></td>
  <tr>
</tbody></table>

我假設您要獲取每一行中的所有列,將它們包裝到單個列中的表中,然后在該行中添加一列。

$('tr').each( function() {
   $(this).children().wrapAll('<td><table><tr></tr></table></td>');
   $(this).append('<td><input type="button" value="click1"></td>');
});
<script>
$(function(){
    var flowbox_table = $('img.flowbox').wrap('<table />');
    var flowbox_tr = $(flowbox_table).wrap('<tr />');
    var flowbox_td = $(flowbox_tr).wrap('<td />');
});
</script>

使用tr[id^='myitem']進行選擇。

[ ^=' '] selects all elements of the tag with attribute attr that starts with the prefix . 選擇器 [ ^ =' ']選擇屬性為attr且以prefix開頭的tag所有元素。

這是完整的代碼:

<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script>

function template(pStr, pAttrs) {
    return pStr.replace(/{\$([^}]*)\$}/g, function (a, pName) {
        return pAttrs[pName];
    });
}

const TDReplaceTemplate =
"   <td>"                                              + "\n" +
"    <table><tbody>"                                   + "\n" +
"     <tr>{$OrgTD$}</tr>"                              + "\n" +
"    </tbody></table>"                                 + "\n" +
"   </td>"                                             + "\n" +
"   <td><input type=\"button\" value=\"click1\"></td>" + "\n";

$(document).ready(function() {
    $("tr[id^='myitem']").each(function(aTR) {
        const aOrgTD = $(this).html();
        const aNewTD = template(TDReplaceTemplate, { OrgTD: aOrgTD } );
        $(this).html(aNewTD);
    });
});
</script>
</head>
<body>
<table><tbody>
  <tr id="myitem1"><td>I need a coat1</td></tr>
  <tr id="myitem2"><td>I need a coat2</td></tr>
</tbody></table>
</body>
</html>

希望這可以幫助。

暫無
暫無

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

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