簡體   English   中英

每行只能單擊一個按鈕

[英]Only ONE button can be clicked per row

我正在嘗試編碼,每個ROW只能選擇一個按鈕。 我嘗試了太多,這是我做的最接近的。

我可以選擇並取消選擇它。 但是每行只能選擇一個。 我的代碼做什么:

我可以選擇任何按鈕,它將添加一個類,以使其變為紅色。 所以現在選擇此按鈕。 我也可以取消選擇它。

這是我的代碼:

$('.btn').click(function(){
        if ($(this).attr('data-selected') === 'true') {
            $(this).attr('data-selected', 'false');
            $(this).removeClass('selected');
        }else {
            $(this).attr('data-selected', 'true');
            $(this).addClass('selected');
        }
    });

<style>
   .selected {
       color:red;
   }
</style>

一些印刷品可以幫助您: 在此處輸入圖片說明

您可以按照以下步驟進行操作。 只需找到其他.btn並從其中刪除.selected ,然后在選擇.btn時將data-selected設置為false .btn 希望這會幫助你。

 $('.btn').click(function () { if ($(this).attr('data-selected') === 'true') { $(this).attr('data-selected', 'false'); $(this).removeClass('selected'); } else { $(this).closest('tr').find('.btn').not(this) .removeClass('selected').attr('data-selected', 'false'); $(this).attr('data-selected', 'true'); $(this).addClass('selected'); } }); 
 .selected { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>1</td> <td>2</td> <td><input type="button" value="1.22" class="btn"/></td> <td><input type="button" value="1.33" class="btn" /></td> <td><input type="button" value="1.44" class="btn" /></td> </tr> <tr> <td>1</td> <td>2</td> <td><input type="button" value="1.22" class="btn" /></td> <td><input type="button" value="1.33" class="btn" /></td> <td><input type="button" value="1.44" class="btn" /></td> </tr> </table> 

為什么不只是制作看起來像按鈕的單選按鈕,如果給它們起相同的名稱,它們將已經具有您要尋找的內置功能。

http://jsfiddle.net/DIRTY_SMITH/YB8UW/616/

    <ul class="donate-now">
<li>
    <input type="radio" id="a25" name="amount" />
    <label for="a25">$25</label>
</li>
<li>
    <input type="radio" id="a50" name="amount" />
    <label for="a50">$50</label>
</li>
<li>
    <input type="radio" id="a75" name="amount" checked="checked" />
    <label for="a75">$75</label>
</li>
<li>
    <input type="radio" id="a100" name="amount" />
    <label for="a100">$100</label>
</li>

</ul>
<br>
<ul class="donate-now">
<li>
    <input type="radio" id="b25" name="amountb" />
    <label for="b25">$25</label>
</li>
<li>
    <input type="radio" id="b50" name="amountb" />
    <label for="b50">$50</label>
</li>
<li>
    <input type="radio" id="b75" name="amountb" checked="checked" />
    <label for="b75">$75</label>
</li>
<li>
    <input type="radio" id="b100" name="amountb" />
    <label for="b100">$100</label>
</li>

</ul>

我為您制作了一個可以用於多行的示例: https : //jsfiddle.net/448feo3j/

$('.button-default').click(function() {
    $(this).parents('tr').find('.button-default').removeClass('button-clicked').attr('data-selected', false);
    $(this).addClass('button-clicked').attr('data-selected', true);
});

暫無
暫無

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

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