簡體   English   中英

如何在特定單元格或表格的 td 中添加多個輸入?

[英]How to add multiple inputs in specific cell or table's td?

我有一張表,我想在第一行的第三列添加多個輸入。 如果我單擊添加 pk1 按鈕,它不會被添加到特定的 td 中,即<td class=partition1>任何使用 jQuery 或 Javascript 的解決方案? 輸入必須在顯示中添加:塊模式而不是內聯模式。 使用 Jquery 或 javascript 最簡單的方法是什么?

 $('.add-pkey1').on('click','.partition1',function(){ var t0 = $('.partition1').append('<input type="text" name="input1" value="test" />'); $('#table-id').append(t0); })
 table { border-collapse: collapse; margin: 1em; } thead { background-color: lightblue; } td, th { border: solid grey 1px; padding: 1em; text-align: center; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="table-id" > <thead > <tr> <th colspan="6" class="text-center"> <span>Source: </span> </th> </tr> <tr> <th>input1</th> <th>input2</th> <th class="partition1">Partition1</th> <th class="partition2"> Partition2 </th> </tr> </thead> <tbody> <tr> <td> <input id="input1" type="text" name="input1" /> </td> <td> <input id="input2" type="text" name="input2" /> </td> <td class="partition1"> <input type="text" name="partition" /> </td> <td class="partition2"> <input type="text" name="partition2" /> </td> </tr> </tbody> </table> <button class="add-pkey1">add pk1</button>

JsFiddle: -https://jsfiddle.net/shreekantbatale2/zfus24m9/1/

正如@Taplar 之前所說,您的代碼存在多個問題,因此我不會一一討論。 但我會提到值得注意的。

  • .on()接受一個事件、選擇器、數據和處理程序,但在您的情況下,您只需要其中兩個,因此它應該是.on('click', function(){})而不是當前版本。
  • 要將元素添加到第三列,您需要做的就是將特定元素的 class 或 id 和 append 所需的元素放入其中。 但是你在那里做了什么會導致 append 另一個<th>到你的表中,這意味着它會自動將新元素添加到新行並會破壞表結構,因為有 4 列並且你想添加<th>在第 3 列和第 4 列之間。
  • partition1在您的 HTML 中不是唯一的 class因此,每當您嘗試向其中添加內容時,它都會添加到兩個不同的位置。

這是您正在尋找的解決方案:

 $('.add-pkey1').on('click', function() { $('.partition1.column3').append('<input type="text" name="input1" value="test" />'); })
 table { border-collapse: collapse; margin: 1em; } thead { background-color: lightblue; } td, th { border: solid grey 1px; padding: 1em; text-align: center; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="table-id"> <thead> <tr> <th colspan="6" class="text-center"> <span>Source: </span> </th> </tr> <tr> <th>input1</th> <th>input2</th> <th class="partition1">Partition1</th> <th class="partition2"> Partition2 </th> </tr> </thead> <tbody> <tr> <td> <input id="input1" type="text" name="input1" /> </td> <td> <input id="input2" type="text" name="input2" /> </td> <td class="partition1 column3"> <input type="text" name="partition" /> </td> <td class="partition2"> <input type="text" name="partition2" /> </td> </tr> </tbody> </table> <button class="add-pkey1">add pk1</button>

暫無
暫無

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

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