[英]Why does JQuery show() function only work on one (rather than all) of elements with the selector?
In the following SSCCE, there is a <table>
nested inside another <table>
. 在下面的SSCCE中,有一个
<table>
嵌套在另一个<table>
。
The question is about the click
listener for #add
button. 问题是关于
#add
按钮的click
监听器。 Specifically, the last if/else
block of the function. 具体来说,函数的最后一个
if/else
块。 When you run this code, click the Add TextField
button once (or more times), and you will see that the #remove
button on which show()
should be executed, is only shown for the first matched selector , and not both (or all) of them. 当你运行该代码,请点击
Add TextField
按钮一次(或多次),你会看到#remove
上的按钮show()
应执行,只显示第一个匹配的选择 ,而不是两个(或他们全部。
Ideally the Remove TextField
should be shown for all the #remove
selectors. 理想情况下,应该为所有
#remove
选择器显示 Remove TextField
。
The question is why? 问题是为什么? How do I fix this?
我该如何解决?
$(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>
That's because you're using id
for a group of objects. 那是因为您将
id
用于一组对象。 id
should be unique per document. 每个文件的
id
应该是唯一的。 You should use a class name instead. 您应该改用类名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.