【问题标题】:displaying button only for the checkbox checked. js jquery仅为选中的复选框显示按钮。 js jquery
【发布时间】:2017-06-18 14:15:50
【问题描述】:

我有一个复选框,onclick 显示一个按钮,但是一次只能单击一个复选框;当我单击复选框时,它会显示所有行的按钮。并且当我单击一个复选框并且同时如果我选中下一个复选框时,它会继续显示按钮(对于选中的最后一个复选框),即使它现在没有选中。对不起,如果我不清楚,请查看下面的测试代码以获取更多信息.选中的复选框只应出现一个按钮,如果未选中的按钮不应出现。任何帮助将不胜感激。

$(document).on('click', ".your", function() {
   $('.your').not(this).prop('checked', false);	//this will make only on checkbox to be checked	
   $('.deleteButton').toggle(this.checked);
		});
.testtable{
border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="testtable">
</th>
<tr>testcolumn</tr>
</th>
<tr><td>
<input type="checkbox"  class="your" value="yourCheckBoxVal">
<input type="button"  class="deleteButton" style="display:none">		
</td></tr>
<tr><td>
<input type="checkbox"  class="your" value="yourCheckBoxVal">
<input type="button"  class="deleteButton" style="display:none">		
</td></tr>
</td></tr>
<tr><td>
<input type="checkbox"  class="your" value="yourCheckBoxVal">
<input type="button"  class="deleteButton" style="display:none">		
</td></tr>

</table>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    由于复选框和按钮都在同一级别,您可以使用$.siblings() 仅切换它。但你必须先隐藏其他人。一个好的做法是通过将按钮分配给一个变量来缓存按钮,以便在微观层面上获得更好的性能。

    $(document).on('click', ".your", function() {
    
       $('.your').not(this).prop('checked', false);		
       // hide all 
       $('.deleteButton').hide();
       // show only this
       $(this).siblings('.deleteButton').toggle(this.checked);
    
    });
    .testtable{
    border:1px solid black;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="testtable">
    </th>
    <tr>testcolumn</tr>
    </th>
    <tr><td>
    <input type="checkbox"  class="your" value="yourCheckBoxVal">
    <input type="button"  class="deleteButton" style="display:none">		
    </td></tr>
    <tr><td>
    <input type="checkbox"  class="your" value="yourCheckBoxVal">
    <input type="button"  class="deleteButton" style="display:none">		
    </td></tr>
    </td></tr>
    <tr><td>
    <input type="checkbox"  class="your" value="yourCheckBoxVal">
    <input type="button"  class="deleteButton" style="display:none">		
    </td></tr>
    
    </table>

    【讨论】:

    • $(this).siblings('.deleteButton').show(); 无论复选框的状态如何(选中或未选中),都会显示复选框附近的按钮。您应该切换它的可见性。
    • Adam 感谢您的努力,但您的代码仍然存在一个问题。当我单击复选框并取消选中它时,按钮不会消失(继续显示)。请帮忙
    猜你喜欢
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多