带变量的动态addEventListener

时间:2017-09-07 16:24:03

标签: javascript html

我正在尝试创建一个表格,我可以在其中添加在单元格中包含文本框的行。然后根据页面上的前4个单元格和另外两个文本框在最后3个单元格中进行一些计算。

我遇到的问题是知道如何将keyup上的活动文本框id传递给我的dynPaybackCalc函数,这样我就可以在计算时定位正确的文本框,因为它目前仅适用于最后一行。如果我想修改任何以前的行,我就不能。

我猜我可以在insRow函数中添加addEventListener但添加任何变量会禁用该函数,并且不会添加任何行。

e.g

function dynPaybackCalc(id) {....

function insRow() {...
var len = 
...inp0.addEventListener("keyup", dynPaybackCalc(len), false);

见insRow& dynPaybackCalc函数。

任何帮助都会很棒。

感谢。

      <!DOCTYPE html>
    <html lang="en">

    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

        <!--<link rel="stylesheet" href="css/style.css" type="text/css">-->
    </head>

    <body>


        <!--PAYBACK CALCULATOR-->
        <div id="paybackCalculator" class="container pb-5">
            <h1 class="text-center">PAYBACK CALCULATOR</h1>

            <div class="text-center pt-3">
                <h2>Building Details</h2>
            </div>

            <!--FORM BURNING HOURS-->
            <form name="frm_PBCalc">

                <h4 class="text-center pt-4">Burning Hours / Energy Tariff</h4>
                <div class="form-group">
                    <div class="row">
                        <div class="col-md-6">
                            <label>Burning Hours</label>
                            <input class="form-control" id="burningHours" placeholder="Your annual operation hours">
                            <small class="form-text text-muted">Enter your current annual lighting operation hours.</small>
                        </div>
                        <div class="col-md-6">
                            <label>Energy Tariff Rate</label>
                            <input class="form-control" id="energyTariff" placeholder="Your Energy Tariff eg: £0.13">
                            <small class="form-text text-muted">Enter you current energy tariff rate</small>
                        </div>
                    </div>
                </div>
            </form>
        </div>


        <!--TABLE Luminaire calculator-->
        <div class="container">
            <h2 class="text-center">Luminaire Calculator (Not Working)</h2>
            <p>To add a luminaire press the new luminaire button below the table.</p>

            <form name="frm_luminaireTable">
                <div class="form-group text-center">
                    <table id="luminaireTable" class="table text-center">
                        <thead>
                            <tr>
                                <th>Qty</th>
                                <th>Current Wattage</th>
                                <th>Proposed Wattage</th>
                                <th>Luminaire Cost</th>
                                <th>Energy Saving</th>
                                <th>Money Saving</th>
                                <th>Payback (years)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>
                                    <input class="form-control" id="mQty" placeholder="Quantity eg: 10">
                                </td>
                                <td>
                                    <input class="form-control" id="mCurrentWatts" placeholder="Current Wattage eg: 54w">
                                </td>
                                <td>
                                    <input class="form-control" id="mProposedWatts" placeholder="Proposed Wattage eg: 22w">
                                </td>
                                <td>
                                    <input class="form-control" id="mLuminaireCost" placeholder="Luminaire Cost eg: £49.99">
                                </td>
                                <td>
                                    <input class="form-control" id="mEnergySave" placeholder="" readonly>
                                </td>
                                <td>
                                    <input class="form-control" id="mMoneySave" placeholder="" readonly>
                                </td>
                                <td>
                                    <input class="form-control" id="mPayback" placeholder="" readonly>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <input class="btn btn-success" type="button" name="addRow" value="Add New Row" onClick="insRow();">
                <input class="btn btn-success" type="button" name="deleteRow" value="Delete Row" onClick="DeleteFunction();">
            </form>
        </div>


        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
        <!--TEXT MANIPULATIONS JS-->
        <!--<script src="scripts/stringManipulations.js"></script>-->


        <script>
            /*KeyUp Listners for the Burning Hours & Energy Tariff*/
            $('#burningHours').keyup(function() {
                paybackCalc();
            });
            $('#energyTariff').keyup(function() {
                paybackCalc();
            });


            /*KeyUp Listners for the first row in table*/
            $('#mQty').keyup(function() {
                mPaybackCalc();
            });

            $('#mCurrentWatts').keyup(function() {
                mPaybackCalc();
            });

            $('#mProposedWatts').keyup(function() {
                mPaybackCalc();
            });

            $('#mLuminaireCost').keyup(function() {
                mPaybackCalc();
            });


            /*PAYBACK CALCULATOR FIRST ROW*/
            function mPaybackCalc() {
                /*vars*/
                var _engTariff, _burninghours, mQty, mCurrentWatts, mProposedWatts, mLuminaireCost;

                /*Gets the values of the text boxes*/
                _burninghours = parseFloat($('#burningHours').val());
                _engTariff = parseFloat($('#energyTariff').val());
                mQty = parseFloat($('#mQty').val());
                mCurrentWatts = parseFloat($('#mCurrentWatts').val());
                mProposedWatts = parseFloat($('#mProposedWatts').val());
                mLuminaireCost = parseFloat($('#mLuminaireCost').val());

                /*Calculations*/
                var wattageDifference = ((mCurrentWatts - mProposedWatts) * _burninghours) / 1000;
                var moneySaving = wattageDifference * _engTariff;
                var payback = mLuminaireCost / moneySaving;

                /*Put calculations into textboxes on screen*/
                $('#mEnergySave').val(wattageDifference.toFixed(1).concat("w"));
                $('#mMoneySave').val("£".concat(moneySaving.toFixed(2)));
                $('#mPayback').val(payback.toFixed(1));
            }


            /*PAYBACK CALCULATOR DYNAMIC*/
            function dynPaybackCalc() {
                /*Text box values to vars*/
                var _engTariff, _burninghours, mQty, mCurrentWatts, mProposedWatts, mLuminaireCost;


                var table = document.getElementById('luminaireTable');
                var rowNumber = table.rows.length - 1;

                /*Gets the values of the text boxes*/
                _burninghours = parseFloat($('#burningHours').val());
                _engTariff = parseFloat($('#energyTariff').val());
                mQty = parseFloat($('#mQty' + rowNumber).val());
                mCurrentWatts = parseFloat($('#mCurrentWatts' + rowNumber).val());
                mProposedWatts = parseFloat($('#mProposedWatts' + rowNumber).val());
                mLuminaireCost = parseFloat($('#mLuminaireCost' + rowNumber).val());

                /*Calculations*/
                var wattageDifference = ((mCurrentWatts - mProposedWatts) * _burninghours) / 1000;
                var moneySaving = wattageDifference * _engTariff;
                var payback = mLuminaireCost / moneySaving;

                /*Put calculations into textboxes on screen*/
                $('#mEnergySave' + rowNumber).val(wattageDifference.toFixed(1).concat("w"));
                $('#mMoneySave' + rowNumber).val("£".concat(moneySaving.toFixed(2)));
                $('#mPayback' + rowNumber).val(payback.toFixed(1));

                alert(textbox);
            }


            /*INSERT A ROW - CLONES THE FIRST ROW AND ADDS IT TO THE END CLEARING ANY INPUTTED VALUES*/
            function insRow() {
                var x = document.getElementById('luminaireTable');
                // deep clone the targeted row
                var new_row = x.rows[1].cloneNode(true);
                // get the total number of rows
                var len = x.rows.length;

                // grab the input from the first cell and update its ID and value
                var inp0 = new_row.cells[0].getElementsByTagName('input')[0];
                inp0.id += len;
                inp0.value = ''
                inp0.addEventListener("keyup", dynPaybackCalc, false);

                var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
                inp1.id += len;
                inp1.value = '';
                inp1.addEventListener("keyup", dynPaybackCalc, false);

                var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
                inp2.id += len;
                inp2.value = '';
                inp2.addEventListener("keyup", dynPaybackCalc, false);

                var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
                inp3.id += len;
                inp3.value = '';
                inp3.addEventListener("keyup", dynPaybackCalc, false);

                var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
                inp4.id += len;
                inp4.value = '';

                var inp5 = new_row.cells[5].getElementsByTagName('input')[0];
                inp5.id += len;
                inp5.value = '';

                var inp6 = new_row.cells[6].getElementsByTagName('input')[0];
                inp6.id += len;
                inp6.value = '';

                // append the new row to the table
                x.appendChild(new_row);
            }

            /*TODO DELETE SELECTED ROW*/
            /*Delete the last row*/
            function DeleteFunction() {
                var table = document.getElementById("luminaireTable");
                var lastPos = table.rows.length - 1;

                if (lastPos != 1) {
                    document.getElementById("luminaireTable").deleteRow(lastPos);
                }
            }
        </script>

    </body>

    </html>

1 个答案:

答案 0 :(得分:0)

使用匿名函数。

*args