簡體   English   中英

如何為每個jquery兄弟的add / sub值創建click事件

[英]How to make a click event for add/sub value for each jquery sibling

我正在嘗試,但是未能通過單擊添加/子按鈕使jquery事件增加/減少輸入值。 它將分別為每一行工作。

 <tr>
    <td>
        <button id="SUB">SUB</button>
        <input type="number" name="" id="" value="1">
        <button id="ADD">ADD</button>
    </td>
    <td>
        <button id="SUB">SUB</button>
        <input type="number" name="" id="" value="1">
        <button id="ADD">ADD</button>
    </td>
    <td>
        <button id="SUB">SUB</button>
        <input type="number" name="" id="" value="1">
        <button id="ADD">ADD</button>
    </td>
    <td>
        <button id="SUB">SUB</button>
        <input type="number" name="" id="" value="1">
        <button id="ADD">ADD</button>
    </td>
</tr>
 $(document).on('click', '#add', function(){
    var value  = $(this).siblings('input').val();
    $(this).siblings('input').value = ++value;
 });
 $(document).on('click', '#sub', function(){
    var value  = $(this).siblings('input').val();
    $(this).siblings('input').value = --value;
 });

您需要使用.val()方法來獲取/設置其輸入值。

HTML中的標識符必須唯一 ,我建議您為按鈕元素分配通用類,並使用類選擇器('.class')來定位它們。

 $(document).on('click', '.add', function() { $(this).siblings('input').val(function(_, value) { if (value == undefined) return 0; return parseInt(value, 10) + 1; }); }); $(document).on('click', '.sub', function() { $(this).siblings('input').val(function(_, value) { if (value == undefined) return 0; return parseInt(value, 10) - 1; }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td> <button class="sub">SUB</button> <input type="number" name="" id="" value="1"> <button class="add">ADD</button> </td> <td> <button class="sub">SUB</button> <input type="number" name="" id="" value="1"> <button class="add">ADD</button> </td> <td> <button class="sub">SUB</button> <input type="number" name="" id="" value="1"> <button class="add">ADD</button> </td> <td> <button class="sub">SUB</button> <input type="number" name="" id="" value="1"> <button class="add">ADD</button> </td> </tr> </table> 

請嘗試這個-

$(this).siblings('input').val(--value);

代替-

$(this).siblings('input').value = --value;

暫無
暫無

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

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