簡體   English   中英

為什么使用選擇器JQuery show()函數僅對一個(而不是全部)元素起作用?

[英]Why does JQuery show() function only work on one (rather than all) of elements with the selector?

JSFiddle

在下面的SSCCE中,有一個<table>嵌套在另一個<table>

問題是關於#add按鈕的click監聽器。 具體來說,函數的最后一個if/else塊。 當你運行該代碼,請點擊Add TextField按鈕一次(或多次),你會看到#remove上的按鈕show()應執行,只顯示第一個匹配的選擇 ,而不是兩個(或他們全部。

理想情況下,應該為所有#remove選擇器顯示 Remove TextField

問題是為什么? 我該如何解決?

 $(document).on("click", "button#add", function() { event.preventDefault(); var parentTable = $(this).parent().parent().parent().parent().parent().parent().parent().parent(); var lastTableRow = parentTable.children('tbody').children('tr:last'); //Adding the new row parentTable.children('tbody').append(lastTableRow.clone()); //Reset lastRow variable lastTableRow = parentTable.children('tbody').children('tr:last'); //Reset the fields lastTableRow.find('table tbody tr td input').each(function() { $(this).val(''); }); //update numberOfRows variable var numberOfRows = parentTable.children('tbody').children('tr').length; alert("numberOfRows:" + numberOfRows); //check if (!(numberOfRows > 1)) { $("#remove").hide(); } else { $("#remove").show(); } }); 
 #outer-table { padding: 20px; border: 3px solid pink; } #inner-table { border: 3px solid orange; } #remove { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="outer-table"> <tbody> <tr> <td> <table id="inner-table"> <tbody> <tr> <td> <p style="display:inline-block">Enter first complain:</p> <input type="text" /> </td> </tr> </tbody> <tfoot> <tr> <td> <button id="add">Add Textfield</button> <button id="remove">Remove Textfield</button> </td> </tr> </tfoot> </table> </td> </tr> </tbody> <tfoot> <tr> <td>Table Footer</td> </tr> </tfoot> </table> 

那是因為您將id用於一組對象。 每個文件的id應該是唯一的。 您應該改用類名。

暫無
暫無

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

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