首页 > 解决方案 > jQuery "this" apparently not selecting unique instance

问题描述

I'm trying to understand why clicking on the "Price" input only works on the first instance. If I add other instances, they don't produce the value. That seems like a good description of the problem, but I am prompted to write more!

$('#add-line').click(function() {
    var lastItem = $(this).prev();
    var lastItemNumber = lastItem.attr("data-income-line");
    var nextItemNumber = parseInt(lastItemNumber) + 1;
    lastItem.clone().attr('data-income-line', nextItemNumber).insertAfter(lastItem);
});

// addition
$('.total').click(function () {
    var line = $(this).parent().parent();
    var price = line.find("input[name='price']").val();
    var quantity = line.find("input[name='quantity']").val();
    var total = parseInt(price) * parseInt(quantity);
    line.find("input[name='total']").val(total);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="income-line" data-income-line="1">                            
    <div class="item-wrapper income-name">
        name<input type="text" name="item_name" />
    </div>
    <div class="item-wrapper income-price">
        price<input type="text" name="price" />
    </div>
    <div class="item-wrapper income-x">
        X
    </div>
    <div class="item-wrapper income-quantity">
        quantity<input type="text" name="quantity" class="quantity" />
    </div>
    <div class="item-wrapper income-total">
        total<input type="text" name="total" class="total"/>
    </div>        
    <div style="clear:left"></div>
</div>
<div id="add-line" class="add-line">
    add
</div>

标签: jquery

解决方案


The problem is that the click handler is only created for the first .total. For elements that are created at a later time, you should rely on event delegation. Use on:

$(document).on('click', '.total', function () {
    // ...etc
})

推荐阅读