将行值乘以输入值

时间:2016-07-01 13:39:10

标签: javascript

我有以下HTML

<form><input type="number"></form>
<table class="my-table">
<thead>
    <tr>
        <td>Header 1</td>
        <td>Header 2</td>
    </tr>
</thead>
<tbody>
    <tr data-row-num="1">
        <td>Item 1</td>
        <td>£0</td>
    </tr>
    <tr data-row-num="1">
        <td>Item 2</td>
        <td>£5</td>
    </tr>
    <tr data-row-num="1">
        <td>Item 3</td>
        <td>£10</td>
    </tr>
</tbody>

我需要通过上面输入的值将每个td:last-child的值复用,并显示新的值。我有js的实验,但我真的很糟糕

<script type="text/javascript">
$('input[type=number]').on("input", function () {
var tr = $('input[type=number]').closest('tr');
var num = this.value;
var numerator = tr.find('td:second-child').text();
tr.find('td:last-child').text('£' + num * numerator);

});

非常感谢你!

1 个答案:

答案 0 :(得分:0)

将您的价格设为span,以便更好地展示selector,并使用jQuery .each()来循环显示价格

<html>
    <head>
        <script src="//code.jquery.com/jquery-2.2.4.js" type="text/javascript"></script>
    </head>
    <body>
        <form id="myForm"><input type="number" id="myNumber" value="5"><input type="submit" value="Do"></form>
        <table class="my-table">
            <thead>
                <tr>
                    <td>Header 1</td>
                    <td>Header 2</td>
                </tr>
            </thead>
            <tbody>
                <tr data-row-num="1">
                    <td>Item 1</td>
                    <td>£<span class="price">10</span></td>
                </tr>
                <tr data-row-num="1">
                    <td>Item 2</td>
                    <td>£<span class="price">100</span></td>
                </tr>
                <tr data-row-num="1">
                    <td>Item 3</td>
                    <td>£<span class="price">1000</span></td>
                </tr>
            </tbody>
        </table>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#myForm ').submit(function (e) {
                    e.preventDefault();

                    // add attribute 'step="0.01"' to input, if you need to use parseFloat()
                    var input = parseInt($(this).find('#myNumber').val());
                    $('.my-table tr td > span.price').each(function (k, item) {
                        var current = parseInt($(item).text());
                        $(item).text(current * input);
                    });
                    return false;
                });
            });
        </script>
    </body>
</html>

Fiddle